前端请求设置credentials: ‘include‘导致的cors问题
1.背景
前端请求设置credentials: ‘include‘其实主要是为了发送凭证,传cookie给后端
2.前端请求
fetch('http://frontend.com', {
method: 'GET', // 或其他HTTP方法
credentials: 'include', // 不携带凭证
headers: {
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
3.后端响应头字段Access-Control-Allow-Origin设置为 “*”,后端域名:http://backend.com
res.headers['Access-Control-Allow-Origin'] = "*";
4.报错
Access to fetch at 'http://backend.com/getDemo?Page=1&PageSize=10' from origin 'http://frontend.com' has been blocked by CORS policy: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'.
5.解决方法,后端响应头字段Access-Control-Allow-Origin字段必须设置前端请求的域名
res.headers['Access-Control-Allow-Origin'] = "http://frontend.com";