Vuecli2 cross-domain problem solving: Access to XMLHttpRequest at'httplocalhost

What is a cross domain issue

When any of the protocol, domain name, and port of a request url is different from the current page url, it is cross-domain.
Cross-domain is due to the restrictions of the same-origin policy of the browser, which is a security mechanism of the browser, and there is no cross-domain between servers.

When I was writing a laboratory project, the interface provided to me by the backend was not mounted on the server. It used port 8001, but the port set by my vue project was 8081, which also caused a cross-domain problem.

Solution

1. Find the vue.config.js file in the root directory of the vue project (if there is no such file, create it yourself), set the cross-domain in the proxy, set the address to be accessed in the proxy, and rewrite /api to be an empty character string. Below is the code in my vue.config.js

const {
    
     defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
    
    
  transpileDependencies: true,
  // const { defineConfig } = require('@vue/cli-service')
//在vue中使用proxy进行跨域的原理是:
//将域名发送给本地的服务器(启动vue项目的服务,loclahost:8080),
//再由本地的服务器去请求真正的服务器。
  devServer:{
    
    
    proxy:{
    
    
      '/api':{
    
    //表示拦截以/api开头的请求路径
        target:'http://localhost:8001',
        changOrigin: true,//是否开启跨域
        pathRewrite:{
    
    
          '^/api':'' //重写api,把api变成空字符,因为我们真正请求的路径是没有api的
        }
      }
    }
  }

})

2. Set baseURL to api when axios.create

//设置请求根路径
axios.defaults.baseURL = '/api'

Now call the backend interface and find that it can be called successfully, solve
insert image description here

Guess you like

Origin blog.csdn.net/qq_63524016/article/details/130175636