vue中解决跨域的问题

152 阅读1分钟

出现跨域的主要是因为浏览器的同源策略,所以只要在中间设置一个代理请求,就可以避开跨域问题

解决步骤:

1. 在vue项目中建一个vue.config.js文件

image.png

2. 通过属性devServer下面的proxy代理实现请求的转发

module exports = {
    devServer:{
        open:true,
        proxy:{    //配置跨域
            '/api':{
                target:"http://10.161.58.92:3000",  //自己的Ip地址
                ws:true,
                changeOrigin: true,    //允许跨域
                pathRewrite:{
                    '^/api':'/api'     //请求的时候用这个api就可以
                }
            }
        }
    }
 }