vue cli3 跨域代理问题

Vue cli3 跨域代理问题

遇到过很多次vue 跨域代理问题,今天来好好写一写解决方法。

vue.config.js(没有的话就自己创建,在根目录下,与package.json同级)
在这里插入图片描述

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': ''
                }
            }
        }
    }
 }

然后在axios配置文件中配置baseURL

axios.defaults.baseURL = '/api'

接下来,如果要使用,则在相应的方法中,直接调用/auth/login接口就行了,如下:

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

然后代理就配置好了。

猜你喜欢

转载自blog.csdn.net/yh0016/article/details/115120781