Home Web Front-end JS Tutorial About Vue's ideas for solving cross-domain routing conflicts

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

Jun 29, 2018 pm 05:29 PM
vue Cross domain routing

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'
   }
  },
Copy after login

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'
   },
  },
Copy after login

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':'/'
    }
   },
  },
Copy after login
Copy after login

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);
  })
 }
Copy after login

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'
Copy after login

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/'
}
Copy after login
Copy after login

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
Copy after login
Copy after login

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);
  })
 }
Copy after login
Copy after login

Final code

Configure in the agent

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

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/'
}
Copy after login
Copy after login

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')
Copy after login

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
Copy after login
Copy after login

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);
  })
 }
Copy after login
Copy after login

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
}
Copy after login

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

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

Vue.prototype.HOST = '/api'
Copy after login

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('调用失败');
  });
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

How to jump to the div of vue How to jump to the div of vue Apr 08, 2025 am 09:18 AM

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

See all articles