[英]How to get data from cookies that were sent with “httpOnly: true”?
In backend, the cookies are sent as below:在后端,cookies 发送如下:
jwt.sign(
payload,
process.env.JWT_SECRET,
{ expiresIn: 31556926 },
(err, token) =>
res
.cookie("token", token, {
httpOnly: true,
maxAge: 31556926,
})
.json({ success: true, newUser })
);
But in frontend, I cannot get the "token" from cookies.但在前端,我无法从 cookies 获得“令牌”。
It is not shown in Chrome, and it is said that it is because Chrome doesn't set cookies in localhost. Chrome中没有显示,据说是因为Chrome没有在localhost中设置cookies。
I tried to use console.log(document.cookie);
我尝试使用
console.log(document.cookie);
to print it, but nothing showed up in console, and I think it is because the httpOnly
is set to be ture so the cookies are invisible from document.cookie
?打印它,但控制台中没有显示任何内容,我认为这是因为
httpOnly
设置为 ture 所以 cookies 从document.cookie
中不可见?
Then how can I get this "token" from cookies?那我怎样才能从 cookies 得到这个“令牌”呢? I need to send it back (through socket.io) to backend for authentication.
我需要将它(通过socket.io)发送回后端进行身份验证。
Thanks!谢谢!
Cookies set with the HttpOnly
flag are not accessible from JavaScript.使用
HttpOnly
标志设置的Cookies无法从 JavaScript 访问。
But cookies in general are sent to the setting server with every request.但是 cookies 通常会随每个请求发送到设置服务器。 Once the server instructs your browser to store the cookie, the browser will send back the contents in the
Cookie
header of the request.一旦服务器指示您的浏览器存储 cookie,浏览器将发送回请求的
Cookie
header 中的内容。
Based on your code snippet above, it looks like you're using Express.根据您上面的代码片段,您似乎正在使用 Express。 To access the token from the server
从服务器访问令牌
const cookieParser = require('cookie-parser'); // Don't forget to npm install
app.use(cookieParser()); // Before any routes that use the cookie
/* from inside your route handler */
req.cookies.token
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.