简体   繁体   English

如何在不同的节点 js 路由上设置 cookie?

[英]How do i set a cookie on different node js routes?

I'm developing a user based project, using node ( express, mongoose etc. )我正在开发一个基于用户的项目,使用节点(快递、猫鼬等)

I currently use JWT and the token has the user id in it, I know how to send a cookie when someone logs in, but I don't know how to make the cookie work on all routes, like basically when a user is logged in and goes on route /test the cookie is still there.我目前使用 JWT 并且令牌中有用户 ID,我知道如何在有人登录时发送 cookie,但我不知道如何使 cookie 在所有路由上工作,就像基本上当用户登录时一样并继续路由 /test cookie 仍然存在。

I think what I'm trying to achieve is called "session/cookie based authentication", could be wrong idk.我认为我想要实现的称为“基于会话/cookie 的身份验证”,可能是错误的 idk。

Once you set a cookie, from within any route, with一旦您从任何路由中设置了 cookie,

const myCookieValue = 'whatever'
res.cookie('myCookieName', myCookieValue, {
  maxAge: 3600*1000, /* one hour */
  httpOnly: true
})

you can retrieve its value, from within any route, with您可以从任何路由中检索其值,

const myCookieValue = req.cookies.myCookieName || 'yo! no cookie! something is wrong!'

The cookie-parser package makes this possible, handling the gnarliness of the the HTTP header for you. cookie-parser包使这成为可能,为您处理 HTTP 标头的粗糙。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM