关于withCredentials的跨域问题

555 阅读1分钟

报错截图:

跨域问题.png

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 'XXX' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

原因:

后端的Access-Control-Allow-Origin设置的是*,但是前端却设置了withCredentials:true来用于传递cookie信息

解决方法:

1.前端放弃传递cookie信息,withCredentials设置为false,

2.后端要设置Access-Control-Allow-Origin为前端的源地址,例如http://localhost:8080,不能是*,而且还要设置header(‘Access-Control-Allow-Credentials: true’);