Home  >  Article  >  Web Front-end  >  About Vue’s ideas for solving cross-domain routing conflicts

About Vue’s ideas for solving cross-domain routing conflicts

不言
不言Original
2018-06-29 17:29:471693browse

This article mainly introduces the ideas of Vue to solve the problem of cross-domain routing conflicts. It has certain reference value. Now I share it with you. Friends in need can refer to

Vue.js (pronunciation/ vju/, similar to view) is a progressive framework for building user interfaces. This article gives you a detailed introduction to the analysis of Vue's ideas for solving cross-domain routing conflicts. Friends who need it can refer to it

vue Introduction

Vue. js (pronounced /vjuː/, similar to view) is a progressive framework for building user interfaces.

Vue only focuses on the view layer and adopts a bottom-up incremental development design.

The goal of Vue is to implement responsive data binding and composed view components through the simplest possible API.

Vue is very easy to learn. This tutorial is based on Vue 2.1.8 version test.

When we configure the following proxy in the routing, we can solve the cross-domain problem

proxyTable: {
   '/goods/*': {
    target: 'http://localhost:3000'
   },
   '/users/*': {
    target: 'http://localhost:3000'
   }
  },

This configuration method solves the cross-domain problem to a certain extent, but it will bring some problems ,

For example, our vue route is also named goods, and conflicts will occur at this time.

If there are many interfaces in the project, it will be very troublesome to configure them all here, and it is easy to generate routes. conflict.

Correct posture

If all interfaces are unified and standardized as one entrance, the conflict will be resolved to a certain extent

Unify the above configuration and add /api/ in front of it

proxyTable: {
   '/api/**': {
    target: 'http://localhost:3000'
   },
  },

If we configure it in this way, it will change when using http requests. An api will be added in front of the request. The relative route will also change, and api will be added in front of the interface. , this will also be very troublesome. We can use the following methods to solve this problem

proxyTable: {
   '/api/**': {
    target: 'http://localhost:3000',
    pathRewrite:{
     '^/api':'/'
    }
   },
  },

The above code is to remove our virtual api interface. At this time, when we actually go to the backend to request, it will not After adding the api prefix, when we make a front-end http request, we must also add the api prefix to match the proxy. The code is as follows:

logout(){
  axios.post('/api/users/logout').then(result=>{
   let res = result.data;
   this.nickName = '';
   console.log(res);
  })
 },
 getGoods(){
  axios.post('/api/goods/list').then(result=>{
   let res = result.data;
   this.nickName = '';
   console.log(res);
  })
 }

We can use the baseUrl of axios to directly default to api. In this way, every time we visit, the api prefix will be automatically added, and we do not need to manually write this prefix on each interface.

The configuration in the entry file is as follows:

import Axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, Axios)
Axios.defaults.baseURL = 'api'

If this configuration 'api/' will read the local domain by default

If configured like this, the production and development environments will not be distinguished

Create a new api.config.js in the config folder The configuration file

const isPro = Object.is(process.env.NODE_ENV, 'production')
module.exports = {
 baseUrl: isPro ? 'http://www.vnshop.cn/api/' : 'api/'
}

is then introduced in main.js, which ensures dynamic matching of the production and development definition prefix

import apiConfig from '../config/api.config'
import Axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, Axios)
Axios.defaults.baseURL = apiConfig.baseUrl

After the above configuration, it can be easily accessed in the dom. There is no need to introduce the axios module into any component.

logout(){
  this.$http.post('/users/logout').then(result=>{
   let res = result.data;
   this.nickName = '';
   console.log(res);
  })
 },
 getGoods(){
  this.$http.post('/goods/list').then(result=>{
   let res = result.data;
   this.nickName = '';
   console.log(res);
  })
 }

Final code

Configure in the agent

proxyTable: {
   '/api/**': {
    target: 'http://localhost:3000',
    pathRewrite:{
     '^/api':'/'
    }
   },
  },

Configure api.config.js in config

Create a new api in the config folder .config.js configuration file

const isPro = Object.is(process.env.NODE_ENV, 'production')
module.exports = {
 baseUrl: isPro ? 'http://www.vnshop.cn/api/' : 'api/'
}

I don’t know much about production and development configuration

You can go to dev-server.js to see the configuration code

const webpackConfig = (process.env.NODE_ENV === 'testing' || process.env.NODE_ENV === 'production') ?
 require('./webpack.prod.conf') :
 require('./webpack.dev.conf')

In the main.js entrance Configuration in the file

import apiConfig from '../config/api.config'
import Axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, Axios)
Axios.defaults.baseURL = apiConfig.baseUrl

The gesture of requesting the api in the dom

logout(){
  this.$http.post('/users/logout').then(result=>{
   let res = result.data;
   this.nickName = '';
   console.log(res);
  })
 },
 getGoods(){
  this.$http.post('/goods/list').then(result=>{
   let res = result.data;
   this.nickName = '';
   console.log(res);
  })
 }

PS: Let’s learn through a piece of code Cross-domain settings under vue

1. Cross-domain issues are often involved when developing with vue. In fact, there are files in vue cli for us to set up cross-domain requests.

2. When cross-domain requests cannot be made, we can modify the dev:{} part in index.js in the config folder under the project.

dev: {
  env: require('./dev.env'),
  port: 8080,
  autoOpenBrowser: false,
  assetsSubDirectory: 'static',
  assetsPublicPath: '/',
  proxyTable: {
    '/api': {
      target: 'http://api.douban.com/v2',
      changeOrigin: true,
      pathRewrite: {
        '^/api': ''
      }
    }
  },
  // CSS Sourcemaps off by default because relative paths are "buggy"
  // with this option, according to the CSS-Loader README
  // (https://github.com/webpack/css-loader#sourcemaps)
  // In our experience, they generally work as expected,
  // just be aware of this issue when enabling this option.
  cssSourceMap: false
}

Set the target to the domain name we need to access.

3. Then set the global properties in main.js:

Vue.prototype.HOST = '/api'

4. At this point, we can use this domain name globally, as follows:

var url = this.HOST + '/movie/in_theaters'
  this.$http.get(url).then(res => {
   this.movieList = res.data.subjects;
  },res => {
   console.info('调用失败');
  });

That’s it The entire content of this article is hoped to be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

How to solve the problem of incorrect access path after Vue background image is packaged

Vue-cli proxyTable How to solve the cross-domain problem of the development environment

How to solve the problem of Vue 2.0 opening the project page blank in IE11

The above is the detailed content of About Vue’s ideas for solving cross-domain routing conflicts. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn