在前端获取 cookie [英] Get cookie on front-end
问题描述
我在后端 nodejs(nestjs) 上使用.我在登录后从服务器发送 cookie:
I use on back-end nodejs(nestjs). From the server i send the cookies after login:
res.cookie('token', 'token', {
httpOnly: true
});
这是我的 cors 设置 app.enableCors({credentials: true });
;
作为前端,我使用 reactjs.登录后,服务器将cookies发送到这里:
And this is my cors setting app.enableCors({credentials: true });
;
As front-end i use reactjs. After login the server sent the cookies here:
但我需要在这里获取饼干:
为什么我没有在我显示的地方获取 cookie 以及如何将它们放到那里以保存它们甚至重新加载页面?
But i need to get the cookies here:
Why i don't get the cookies in the place where i showed and how to get them there to save them even o reloading the page?
推荐答案
cookie 未在前端持久化的原因是您可能没有在前端请求中设置 withCredentials
.axios 的一个例子是:
The reason the cookie is not persisted in the frontend is that you are probably not setting the withCredentials
on your frontend request. An example with axios would be:
axios.post('http://localhost:3001', {}, { withCredentials: true })
fetch 的一个例子是:
An example with fetch is:
fetch(url, {
method,
headers: {
'Content-Type': 'application/json'
},
credentials: 'include'
}
注意:出于安全原因,您必须在后端 CORS 配置中明确指定来源,否则您将收到以下错误:
Note: For security reasons you must have explicitly specified the origin on your backend CORS configuration otherwise you will get the following error:
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 做到这一点,您可以通过:
To do that with nest.js/express you can pass:
app.enableCors({
credentials: true,
origin: ['http://localhost:3002', 'your-production-domain']
});
这篇关于在前端获取 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!