vue2 cross-domain problem solving [front-end method]

vue2 cross-domain problem solving [front-end method]

Common cross-domain errors in front-end projects are as follows:

Access to XMLHttpRequest at 'https://xxx.com/ms/' from origin 'http://10.23.30.135:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

We can solve this kind of cross-domain error by setting the Access-Control-Allow-Origin header on the backend, but generally the frontend cannot operate the background service, so it is very inconvenient to implement.

Therefore, you can use vue-cli's built-in configuration method to achieve this.

solve

We can find the devServer attribute in the configuration reference of the vue-cli official website [https://cli.vuejs.org/zh/config/#devserver] to solve cross-domain problems.

In actual projects, we need to do two steps to solve cross-domain issues.

1. Modify the default request address of our axios to /api

axios.defaults.baseURL = '/api'

The above /api will be used as the address that needs to be replaced when we proxy. It can also be defined by itself. When configuring the devServer attribute in vue.config.js later, the corresponding content can be modified simultaneously.

2. Configure devServer properties in vue.config.js

module.exports = {
  devServer: {
    proxy: {
      "/api": {
        target: "[实际请求的目标地址]",
        changeOrigin: true,
        pathRewrite: {
          "^/api": ""
        }
      }
    }
  }
}

Afterwards, restart the project to take effect.

Regarding the issue of obtaining the target address of the actual request above:

For example, the request address you actually request for a certain service is https://www.xxx.com/ms/users/xiaowang. This request address is mainly divided into IP (https://www.xxx.com/ms/) With the interface (/user/xiaowang) you wrote in the front-end project, fill in the request IP (https://www.xxx.com/ms/) in the target attribute above.

Guess you like

Origin blog.csdn.net/qq_44886882/article/details/131070151