在前端获取 cookie
IT技术
node.js
reactjs
nestjs
2021-05-06 14:59:31
1个回答
cookie 没有保留在前端的原因是您可能没有withCredentials
在前端请求中设置 。axios 的一个例子是:
axios.post('http://localhost:3001', {}, { withCredentials: true })
fetch 的一个例子是:
fetch(url, {
method,
headers: {
'Content-Type': 'application/json'
},
credentials: 'include'
}
注意:出于安全原因,您必须在后端 CORS 配置中明确指定来源,否则您将收到以下错误:
Access to XMLHttpRequest at 'http://localhost:3001/' from origin 'http://localhost:3000' has been blocked by CORS policy: 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'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
要使用 nest.js/express 做到这一点,您可以通过:
app.enableCors({
credentials: true,
origin: ['http://localhost:3002', 'your-production-domain']
});
其它你可能感兴趣的问题