前端用的Vue框架,后端给了一个host地址,写到了.env 文件中,http://xxx.xxx.xxx
用axios去请求,看Chrome 控制台报错:
Access to XMLHttpRequest at 'http://xxx.xxx.xxx/api/web/user/info' from origin 'http://localhost:8080' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '*, http://localhost:8080', but only one is allowed.
network 面板显示如下:
response headers中关于跨域的设置重复了。
以为vue.config.js中没有配置devServer呢,加上之后还是报相同的错误:
module.exports = {
publicPath: './',
devServer:{
proxy:{
'/api':{
target:'http://xxx.xxx.xxx/api',
changeOrigin:true,
pathRewrite:{
'^/api':''
}
}
}
}
}
经后端指点,把.env中的域名配置去掉,保留vue.config.js中的代理设置,请求的URL为:
http://localhost:8080/api/web/user/info 。 这样设置后不报跨域错误了,请求成功。
----------------------------------------------------------------------------------------------------------------------
从报的错误看,应该是后端Nginx 和 真实服务器都设置了跨域导致的。第二天让后端把Nginx中的跨域配置去掉,在.env中加上域名配置,vue.config.js 中的devServer配置去掉保留都可以。同样请求成功。
这个问题前端修改和后端修改都可解决。 但具体原因还是不太清楚,有知道的童鞋欢迎留言。