今天在联调后端接口的时候,通过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:trueAccess-Control-Allow-Origin不可以为 *,因为 * 会和 Access-Control-Allow-Credentials:true 冲突通过修改前端和后端都可以解决,具体修改方式取决于项目的具体情况。
因为这个项目前后端交互完全使用token,所以不需要传递cookie了,修改axios配置即可:
// 去掉该配置 // axios.defaults.withCredentials = true;