javascript - 将用户引用到创建的注释 nodejs
问题描述
好吧,所以我一直在创建这个 Web 应用程序,它可以让用户保存笔记(笔记应用程序)我正在使用 express mongoDB 作为后端,我一直在寻找一种方法来引用创建笔记的用户(所以最终每个用户只能检查他自己的笔记)无论如何我看着周围,我没有找到任何方法来访问 jwt 有效负载这是我的代码: notes.js
exports.createNote = (req, res, next) =>{
let note = new Note(req.body);
note.user = req.user;note.save((err) =>{
if(err){
res.status(401);
return next(err)
}
return res.status(201).json('note created successfully!')
})
};
noteSchema.js
let noteSchema = Schema({
title : {type : String, require : true},
description : {type : String, require : true},
User : {type : String, ref : "User", require : true}
});
module.exports = mongoose.model('Note', noteSchema);
身份验证中间件
module.exports = (req, res, next) =>{
const token = req.headers.authorization.split(' ')[1];
const decoded = jwt.verify(token, process.env.SECRET);
const userId= decoded.user._id
try{
if(req.body.userId && req.body.userId !== userId){
throw 'invalid user ID';}}else{
next();
}
}catch{
res.status(401).json({ error : 'not authenticated !'});
}
我想知道有什么方法可以访问note.js文件中的JWT Payload(提取user._id)
解决方案
您可以在身份验证中间件req
中添加有效负载。
module.exports = (req, res, next) =>{
const token = req.headers.authorization.split(' ')[1];
const decoded = jwt.verify(token, process.env.SECRET);
const userId= decoded.user._id
try{
if(req.body.userId && req.body.userId !== userId){
throw 'invalid user ID';}}else{
req.jwtPayload = decoded // add payload here to req
next();
}
}catch{
res.status(401).json({ error : 'not authenticated !'});
}
然后你可以在notes.js中访问它,比如
exports.createNote = (req, res, next) =>{
const { jwtPayload } = req
// do stuff with jwtPayload
let note = new Note(req.body);
note.user = req.user;note.save((err) =>{ // by the way, this will not behave as you expect
// because it is an asynchronous callback
if(err){
res.status(401);
return next(err)
}
return res.status(201).json('note created successfully!')
})
确保您的身份验证中间件在notes.js之前
推荐阅读
- android - Android 图标和单选按钮不遵循日/夜模式
- fortran - fortran coarray 图像访问无法正常工作?
- javascript - 确认输入后如何停止滚动
- python - 如何在 Python 中比较对象属性的值?
- javascript - 如何正确使用 JQuery 选项选择
- google-sheets - 如果 B 列中的内容不为空,如何返回 A 列中名称的最后一次出现
- c# - app.config 程序集绑定似乎被忽略了
- javascript - 传单地图:点击而不是鼠标悬停在标记上的工具提示
- android - Fab 没有被底部导航上方的小吃店向上推
- c++ - 难以配置 Bazel 目标包括和 deps