javascript - 为什么我得到未定义的 jwt 令牌值,因为令牌存储在 cookie 中?
问题描述
服务器服务(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);
解决方案
我想这里的问题是命名
"token"
您在服务器服务上命名 cookie并将其保存。但是然后在 auth-middleware 中,您尝试接收"jwt"
-cookie
作为旁注:
profile saved !!
不是有效的 JSON
推荐阅读
- java - JPA Criteria API - 查询代码在单独执行时有效,但在用作子查询时无效
- python - DPI-1047:找不到 64 位 Oracle 客户端库:“找不到指定的模块”- 不重复
- macos - 无法在 Bot Framework 模拟器上运行本地机器人
- typescript - Nest 无法解决 AuthService 的依赖关系 - 导入模块的问题,该模块使用 Mongoose 和提供者
- python - Python:将 Dataframe 从日期列表转换为 Date From & Date To 格式
- r - 如何在R中将具有0和1的多个变量列转换为是和否
- c# - 使用枚举存储多个真值
- c - Freeing string untill null terminator
- sql - Msg 137, Level 15, State 2, Procedure id_management, Line 13 Must declare the scalar variable "@COMBINE"
- c++ - How to pass method to other method as an argument?