fetch 带cookie跨域访问

前后台分离,用nginx做请求跨域处理。我用了fetch,来替代ajax。访问正常。但是请求时没带cookie,我就加了credentials: "include"

var myHeaders = new Headers();
fetch(url, {
              method: 'GET',
              headers: myHeaders,
              credentials: "include"
            })

这个时候服务端确实拿到了cookie,但是数据返回报错
ERROR :Fetch API cannot load http://localhost:8077/sonny/l... 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.

阅读 22.1k
2 个回答
fetch(url, {
  mode: "no-cors",
})

解决了,在后台添加。允许浏览器
response.setHeader("Access-Control-Allow-Credentials","true");

Access-Control-Allow-Credentials 头 工作中与{domxref("XMLHttpRequest.withCredentials")}} 或Fetch API中的Request() 构造器中的credentials 选项结合使用。Credentials必须在前后端都被配置(即the Access-Control-Allow-Credentials header 和 XHR 或Fetch request中都要配置)才能使带credentials的CORS请求成功。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进