Nodejs中间件用于特定请求

时间:2018-09-19 10:23:25

标签: node.js express

我想要这些路由的中间件:

POST /tickets
PUT /tickets/:id
DELETE /tickets/:id
etc...

但是目前我的中间件在/ tickets等上执行的每个HTTP请求上执行:

app.use('/tickets', function(req, res, next) {

    var token = req.body.token || req.query.token || req.headers['x-access-token'];

    if (token) {
        jwt.verify(token, app.get('superSecret'), function(err, decoded) {      
            if (err) {
                return res.json({ success: false, message: 'Failed to authenticate token.' });    
            } else {
                req.decoded = decoded;    
                next();
            }
    });
 } else {

      return res.status(403).send({ 
          success: false, 
          message: 'No token provided.' 
    });

    }
});

如何在特定请求上使用它?

1 个答案:

答案 0 :(得分:2)

Express具有发布/获取/删除路由的方法。 documentation

的更多内容

您应该编写中间件功能并在路由时重用它。

示例:

function JWTCheckMiddleware(req, res, next) {
  var token = req.body.token || req.query.token || req.headers['x-access-token'];
  if (token) {
    jwt.verify(token, app.get('superSecret'), function(err, decoded) {
      if (err) {
        return res.json({ success: false, message: 'Failed to authenticate token.' });
      } else {
        req.decoded = decoded;
        next();
      }
    });
  } else {
    return res.status(403).send({
      success: false,
      message: 'No token provided.'
    });
  }
});

app.post('/tickets', JWTCheckMiddleware, function createTicket(req, res) {...});
app.put('/tickets/:id', JWTCheckMiddleware, function updateTicket(req, res) {...});
app.delete('/tickets/:id', JWTCheckMiddleware, function removeTicket(req, res) {...});