简体   繁体   English

expressjs-使用中间件功能

[英]expressjs - using middleware function

I would like to know how I can move the following code into a separate function (in the same file) and call upon it when either I call the POST or PUT routes to add or update documents. 我想知道如何将以下代码移动到单独的函数中(在同一文件中),并在我调用POST或PUT路由以添加或更新文档时对其进行调用。

I'm using https://www.npmjs.org/package/express-validator 我正在使用https://www.npmjs.org/package/express-validator

The following is currently in my POST route but when I'm updating a record the title will still need to be validated. 以下内容目前在我的POST路线中,但是当我更新记录时,仍然需要验证标题。

app.post('/docs', auth, function (req, res) {
  req.checkBody('title', 'Title is required').notEmpty();
  var errors = req.validationErrors();

  if(errors){
    res.json(400, { errors: errors });
    return;
  }

  //go ahead and save the document

});

I've tried making my own function but I'm not sure where to put the var errors = req.validationErrors(); 我试着做我自己的函数,但不确定在哪里放置var errors = req.validationErrors(); or whether it's bad practice to return 400 errors from a separate function. 或者从单独的函数返回400个错误是否是错误的做法。

Any help/code much appreciated. 任何帮助/代码非常感谢。

The body of the middleware function is almost identical to the code you are using right now, only with two notable differences: 中间件函数的主体与您当前使用的代码几乎相同,只有两个明显的区别:

  • The function ensures that the req.method is either POST or PUT. 该函数确保req.method是POST或PUT。
  • The next() function is called when validation passes. 验证通过时将调用next()函数。 This will trigger the next middleware function in the chain, or the route handler. 这将触发链中的下一个中间件功能或路由处理程序。
app.use('/docs', function(req, res, next) {
  if (req.method == 'POST' || req.method == 'PUT') {
    req.checkBody('title', 'Title is required').notEmpty();
    var errors = req.validationErrors();
    if (errors) {
      res.json(400, { errors: errors });
      return;
    }
  }
  next();
});

app.post('/docs', auth, function (req, res) {
  // go ahead and save the document
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM