Vue cli3 cross-domain proxy problem

Vue cli3 cross-domain proxy problem

I have encountered many vue cross-domain proxy problems, so I will write a solution today.

vue.config.js (if not, create it yourself, in the root directory, at the same level as package.json)
insert image description here

vue.config.js:

module.exports = {
    
    
	devServer: {
    
    
        proxy: {
    
    
            '/api': {
    
    
                // 此处的写法,我访问的是http://localhost:8080/api/dataHome.json设置代理后,axios请求不需要把域名带上,只需要把路径前面加上 /api 即可。
                target: 'http://服务器地址:端口/',
                // 允许跨域
                // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
                changeOrigin: true,

                // 是否代理
                ws: true,

                // 路径重置
                // 由于设置了 pathRewrite,所以请求时会把 /api 替换成 '',最终的请求路径为 /dataHome.json
                pathRewrite: {
    
    
                    '^/api': ''
                }
            }
        }
    }
 }

Then configure the baseURL in the axios configuration file

axios.defaults.baseURL = '/api'

/auth/loginNext, if you want to use it, you can directly call the interface in the corresponding method , as follows:

const {
    
     data: res } = await this.$http.post('/auth/login', {
    
    
       loginName: this.loginForm.user,
       loginPassword: this.loginForm.password,
})

Then the proxy is configured.

Guess you like

Origin blog.csdn.net/yh0016/article/details/115120781