首页 > 解决方案 > 将用户引用到创建的注释 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)

标签: javascriptnode.jsmongodbexpress

解决方案


您可以在身份验证中间件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之前


推荐阅读