【发布时间】:2021-11-03 11:42:43
【问题描述】:
服务器服务(localhost/8000)成功将 jwt 令牌存储在 cookie 中,并将响应 cookie 发送到客户端服务。 cookie 成功存储在客户端服务(localhost/3000)上,但是当我想检索它时,它显示未定义。我还包括 cookie-parser 包,但它仍然显示未定义。
服务器服务:
export const saveprofile = async (req, res) => {
try {
const profile = await new Profile(req.body);
if (req.body.password === req.body.cpassword) {
const token = await profile.generateAuthToken();
res.cookie('token', token, { expires: new Date(Date.now() + 9999999), httpOnly: true })
profile.save();
res.status(200).json('profile saved !!');
}
} catch (error) {
req.status(500).json(error);
}
}
现在当我想通过 auth 函数来控制存储在 cookie 中的令牌时,它显示未定义。
认证函数(中间件)
import jwt from 'jsonwebtoken';
import post from '../schema/post-schema.js'
import profile from '../schema/profile-schema.js';
import Cookies from 'js-cookie';
const auth = async (req, res, next) => {
try {
const token = req.cookies.jwt;
console.log("The token is", token) //it shows undefined
const verifyuser = jwt.verify(token, "mynameismohitkumarfromnationalinstituteoftechnologyagartala");
const user = await profile.findOne({ _id: verifyuser._id });
console.log(verifyuser);
console.log(user);
next();
} catch (error) {
res.status(401).json(error);
}
}
export default auth;
身份验证路由:
router.get('/post/:id', auth, getpost);
【问题讨论】:
-
为什么要使用 res.cookie 和 req.cookies.jwt?你好像在使用 js-cookie,也就是说你应该使用 Cookies.set 和 Cookies.get。
-
你试过控制台记录父对象吗? req.cookies 或者只有 req 对象。
-
是的,我试图控制 req.cookies 它显示为 [Object: null prototype] {}。
-
实际上在网络(开发者工具)中显示状态码为 401 Unauthorized on routing '/post/:id'。
标签: javascript node.js reactjs npm cookies