The following configuration applies only to Vue Cli3.

In a project where the front and back ends are separated, generally during the development process, the front-end application is run at the local localhost, but the API interface is on other hosts at this time, and cross-domain problems will occur when API requests are made.

At this point you need to proxy API requests to the API server in the development environment. This problem can be configured with the devServer.proxy option in vue.config.js.

It’s also easy to use:

The first step

Make sure you have HTTP-proxy-Middleware installed first, so skip this step if you do.

Install the HTTP proxy – middleware:

npm install --save-dev http-proxy-middleware

The second step

Add the following configuration to the vue.config.js file:

module.exports = {
  devServer: {
    proxy: {
      '/api'// Request link match target:'<url>'// API server domain name ws:true// Enable webSockets changeOrigin:true// Enable proxy: create a virtual server locally, and then send the requested data, and receive the requested data at the same time, so that there is no cross-domain problem between the server and the server for data interaction},'/foo'// Another connection matches target:'<other_url>'// API server domain name}}}}Copy the code

The third step

A link request can be written as follows (here is an AXIos request) :

axios.get('/user? ID=12345')
.then(function (response) {
  // handle success
  console.log(response);
})
.catch(function (error) {
  // handle error
  console.log(error);
})
.then(function () {
  // always executed
});
Copy the code

Such requests when the request is for http://localhost:8080/user? ID=12345 will be proxied to API server: https://juejin.cn/user/993614243576685?ID=12345 (assuming the above the second set of domain name is https://juejin.cn/user/993614243576685).

The fourth step

Restart vue-cli-service serve, remember that every time you modify the configuration in vue.config.js file, you must restart the serve.