问题
今天在联调后端接口的时候,通过chrome
调试工具可以看到接口数据返回正常,状态200
,可是返回仍然被axios
的onRejected
拦截了。无法获取请求结果,并在chrome
控制台上可以看到如下错误。
Failed to load http://localhost:8007/wenjuan/1: The value of the ‘Access-Control-Allow-Origin’ header in the response must not be the wildcard ‘*’ when the request’s credentials mode is ‘include’. Origin ‘http://xxxxxgbl.org’ is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
原因
本来用的是代理转发,后来后端调整专用的/api
开头的域名,并允许跨域请求。然后就出现了这个问题。
下图是后端接口的配置。
这里是前端的axios
配置。
知识点
axios
发送请求的时候,默认是不会带上cookie
的,如果需要带cookie
,需要通过设置withCredentials: true
来解决。
并且需要后端配置做如下设置:
header
信息Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin
不可以为*
,因为*
会和Access-Control-Allow-Credentials:true
冲突
解决
通过修改前端和后端都可以解决,具体修改方式取决于项目的具体情况。
因为这个项目前后端交互完全使用token
,所以不需要传递cookie
了,修改axios
配置即可:
// 去掉该配置
// axios.defaults.withCredentials = true;