我想要这些路由的中间件:
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.'
});
}
});
如何在特定请求上使用它?
答案 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) {...});