Vue proxy跨域配置

1,483 阅读1分钟

1. 通过vuecli脚手架创建的项目如果需要增加配置,就自己在项目根目录下建立文件vue.config.js 其他内容和webpack中webpack.config.js写的配置一样正常写.

2. 若需要跨域请求数据时需要自己写配置 即开启代理

module.exports = {
    devServer : {
        proxy : {//译代理
            "/app":{
                target: " http://localhost:3000",  //写访问的地址
                ws: true,  //如果要代理 websockets,配置这个参数
                changeOrigin: true,  //允许跨域
                pathRewrite: {//译改写路径即重写 /app相当于变量 将地址赋予给变量
                    "^/app": "http://localhost:3000"//和target后的地址必须一致
                }
            }
        }
    }
}

3. 使用的时候用/app代替(类似变量),然后这样就可以了。

'/app/top/list?idx=3' 等效于 'http://localhost:3000/top/list?idx=3'

this.axios.get('/app/top/list?idx=3').then(res=>{
           this.crunchiesList1 = res.data.playlist;
     })

平时如果域名相同 又不想多次重复写域名,就可以这样配置,类似配置根域名效果,但是获取数据使用时必须要写配置的变量 不然还是会从webpack默认设置服务器下获取数据。 若想配置多个代理也可以,proxy是个对象继续写就行,/app是自己取名的可以任意命名(/必须要) 多个代理示例:

module.exports = {
    devServer : {
        proxy : {//译代理
            "/app":{
                target: " http://localhost:3000",  //写访问的地址
                ws: true,  //如果要代理 websockets,配置这个参数
                changeOrigin: true,  //允许跨域
                pathRewrite: {//译改写路径即重写 /app相当于变量 将地址赋予给变量
                    "^/app": "http://localhost:3000"
                }
            },
            "/api":{
                target: " http://localhost:3000",
                ws: true,
                changeOrigin: true,
                pathRewrite: {
                    "^/api": "http://localhost:3000"
                }
            }
        }
    }
}

以上就是通过配置proxy解决跨域的方法。