Vue和django的前后端分离项目,之前通过在django中允许跨域访问实现了跨域请求,但为了使每个请求带上session信息,我设置了withCredentials ,即:
axios.defaults.withCredentials = true
然后跨域请求时会出现如下问题:
Response to preflight request doesn’t pass access control check: 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://localhost:8080’ is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
解决方案
Access-Control-Allow-Origin 字段必须指定域名,不能为*
Access-Control-Allow-Credentials为true
main.js中添加拦截器
Vue.http.interceptors.push((request, next) => {
request.credentials = true;
next();
});