javascript - 条件不工作的中间件身份验证 Express。节点.js
问题描述
我目前正在开发一个网站,其中包含我用 node.js、express 和 MongoDb 为数据库构建的 API。
我目前正在学习 node 和 express 并且无法找到创建中间件以验证 USER ID 与 COMMENT 中的 POSTED BY ID 匹配的方法。这样用户只能删除他自己的评论。
我的中间件看起来像这样
verifyUserIdPostedBy.js
const Comment = require('../models/Comment');
var userId
var postedById
module.exports = {
verfyUserIdPostedBy: function (req, res, next) {
userId = req.header('userId')
postedById = Comment.findOne({ _id: req.params.commentId}).populate('postedBy') .exec( function (error, body) {
if (error) throw new Error(error);
req.postedById = body.postedBy._id // assign the ID to the req object
console.log(req.postedById);
});
console.log(userId);
if(userId !== req.postedById)
return res.status(500).json({message: 'Stopped'})
return next();
},
}
中间件中的 console.log() 准确地显示了我想要比较的 2 个值,但我收到错误“已停止”并且我的验证从未发生。我尝试使用评论所有者而不是评论所有者来访问路线并且没有任何工作
我的路线看起来像这样 comments.js
const express = require('express');
const router = express.Router();
const Comment = require('../models/Comment');
const verify = require('./verifyToken');
const {verfyUserIdPostedBy} = require('./verfyUserIdPostedBy')
// DELETE COMMENT
router.delete('/:commentId', verify, verfyUserIdPostedBy, async (req, res) => {
try {
const removedComment = await Comment.deleteOne({ _id: req.params.commentId });
res.json(removedComment);
} catch(err){
res.json({message:err});
}
})
就像我说的那样,我对此很陌生,但找不到正确的方法。
提前感谢任何帮助和建议。
马里奥
解决方案
我在您的代码中添加注释来解释它是如何工作的:
verfyUserIdPostedBy: function (req, res, next) {
userId = req.header('userId')
postedById = Comment.findOne({ _id: req.params.commentId}).populate('postedBy') .exec( function (error, body) {
/* -----this is a callback function------ */
/* the code inside the callback function is executed only when findOne finish and **after** the code outside */
if (error) throw new Error(error);
req.postedById = body.postedBy._id // assign the ID to the req object
console.log(req.postedById);
});
/* this code is executed before the code inside the callback function */
console.log(req.postedById); // undefined, you can check
console.log(userId);
if(userId !== req.postedById) // this is always true
return res.status(500).json({message: 'Stopped'}) // and this line always executes
return next(); // and this line never execute
},
这个概念是callback
。我强烈建议你研究这个关键字,回调在 NodeJS 中大量使用。如今,有 Promise 和 async/await 允许开发人员以“同步方式”编写异步代码,但是callback
是基础。
为了使您的代码正常工作,1 个简单的解决方案(有很多解决方案!)将比较代码放入回调块中,例如:
const Comment = require('../models/Comment');
var userId
var postedById
module.exports = {
verfyUserIdPostedBy: function (req, res, next) {
userId = req.header('userId')
postedById = Comment.findOne({ _id: req.params.commentId}).populate('postedBy') .exec( function (error, body) {
if (error) throw new Error(error);
req.postedById = body.postedBy._id // assign the ID to the req object
console.log(req.postedById);
console.log(userId);
if(userId !== req.postedById)
return res.status(500).json({message: 'Stopped'})
return next();
});
},
}
推荐阅读
- security - 如何为 SOAP Web 服务实现 JWT(JSON Web 令牌)?
- java - BranchSDK:用户会话尚未初始化
- ios - 当应用程序终止时,BLE 设备如何调用应用程序
- tensorflow - 如何使用 tqdm 使用 tf.data.Dataset api 可视化训练步骤的进度?
- android - 在由 Room 库创建的 SQLite 数据库所在的 Android 设备上
- c# - 在添加一些为空的新字段时,无法将对象的错误从 DBNull 转换为其他类型?
- angular - 路由更改时组件之间的 BehaviorSubject
- node.js - 从多个集合中填充 Mongoose 文档
- c# - 如果可能,Task.WhenAll 会同时执行任务吗?
- android - 在 Android Oreo 中禁用滑动删除通知