[英]How to find a Forum or a Node by passing a JWT Token?
我想知道如何使用我的 JWT 令牌找到我的论坛
exports.getByOwnerID = function (req, res, next) {
Forum.find({createdBy: req.body.createdBy})
.then(doc => {
if(!doc) { return res.status(400).end();}
return res.status(200).json(doc);
})
.catch(err => next(err));
}
所以在这里我有我的功能来验证我的 JWT 令牌我以这种方式使用它
这是我的路线: router.post('/',verifyToken,getOwner);
这是我的请求:POST http://localhost:8080/forum/getOwner Authorization: Bearer {token}
const extractToken = (rawTokenHeader) => {
if(!rawTokenHeader) { return undefined; }
// Remove bearer and extract token value
const temp = rawTokenHeader.split(' ');
if(!temp || temp.length != 2) { return undefined; }
// Return encoded token
return temp[1];
};
module.exports = function(req,res,next){
// Get authorization header
const rawTokenHeader = req.header('Authorization');
// Get token value
const token = extractToken(rawTokenHeader);
// No token -> No access
if(!token) {
console.log('No token in request');
// Access denied
return res.status(401).send('Access Denied');
}
// Verify token
try {
const decoded = jwt.verify(token, process.env.JWT_KEY);
req.token= decoded;
req.user = decoded;
//console.log(token.userID);
// Proceed
next();
} catch(err) {
console.error('Error in JWT check: ', err);
// Tell client something went wrong
res.status(400).send('Invalid Token');
}
}
const forumSchema = ({
forumName: {
type: String,
required: true,
},
forumDescription: {
type: String,
required: true,
},
createdBy: {
type: Schema.Types.ObjectId, ref: 'User'
},
published_on: {
type: String,
default: moment().format("LLL")
},
});
我已经尝试了很多东西,但我无法解决它了..我需要帮助
我怎么没有足够的声誉来发表评论我留下这个作为答案,如果我们不知道论坛的架构是什么样子以及返回 req.body.createdBy 的内容,很难说为什么这不起作用,但如果 jwt 是由您创建的,您可以在其中对 Forum._id 进行编码,当您在此处收到它时,您可以对其进行解码并在数据库中找到该论坛
编辑 - -
现在我可以看到你得到的错误和论坛的模式我可以说你可以通过导入mongoose.Types.ObjectId(req.body.CreatedBy)
在将解析字符串的查询mongoose.Types.ObjectId(req.body.CreatedBy)
中添加它来解决错误到一个对象 ID
如您所见,您在req
对象中有user
(或token
)数据,我希望您的 jwt 令牌也包含用户的 id。 您可以使用用户 ID 查找他们的论坛。
根据路由器router.post('/', verifyToken, getOwner);
( getByOwnerID
???),让我们更新getOwner
处理程序:
exports.getOwner = function (req, res, next) {
Forum.find({ createdBy: req.user.userID }) // or something like that
.then(doc => {
if(!doc) { return res.status(400).end();}
return res.status(200).json(doc);
})
.catch(err => next(err));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.