在解决fetch跨域请求接口的时候,一般都是让后台接口在返回头里添加
//允许所有域名的脚本访问该资源header("Access-Control-Allow-Origin: *");
确实这样是可以解决跨域请求的问题,但是如果我们要在请求的时候添加session,那么这样设置就会出现问题了。
fetch添加Cookie验证的方法是设置credentials: 'include'fetch(url, { method: 'POST', body: JSON.stringify(params), mode: 'cors', //请求时添加Cookie credentials: 'include', headers: new Headers({ 'Accept': 'application/json', "Content-Type": "application/x-www-form-urlencoded; charset=utf-8", }) })
设置好了之后,信心满满的发起请求。却发现网络请求报错了
A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:3000' is therefore not allowed access
原因是网络请求需要携带Cookie时Access-Control-Allow-Origin是不能设置为*的,这个时候应该要给Access-Control-Allow-Origin指定域名
![image.png image.png](https://upload-images.jianshu.io/upload_images/7981756-5e6f34ea3375efc6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
这样就可以达到跨域请求的同时传递Cookie的目的了
- 列表项目