我想验证我们的所有get请求在其身份验证标头中都有一个特定的标记。
我可以将它添加到我们的get端点:
app.get('/events/country', function(req, res) {
if (!req.headers.authorization) {
return res.json({ error: 'No credentials sent!' });
}
有没有更好的方法在NodeJS / Express中处理这个而不改变每个端点?像过滤前/ AOP方法之类的东西?
答案 0 :(得分:27)
middleware的用途是什么:
app.use(function(req, res, next) {
if (!req.headers.authorization) {
return res.status(403).json({ error: 'No credentials sent!' });
}
next();
});
...all your protected routes...
确保在中间件应该应用的路由之前声明中间件。