node.js 使用 Express 验证请求头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46094417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Authenticating the request header with Express
提问by kambi
I want to verify that all our get requests have a specific token in their authentication header.
我想验证我们所有的 get 请求在他们的身份验证标头中都有一个特定的令牌。
I can add this to our get endpoints:
我可以将其添加到我们的 get 端点中:
app.get('/events/country', function(req, res) {
if (!req.headers.authorization) {
return res.json({ error: 'No credentials sent!' });
}
Is there any better way to handle this in NodeJS/Express without changing every endpoint? something like a before-filter/AOP approach?
有没有更好的方法在 NodeJS/Express 中处理这个而不改变每个端点?类似于过滤前/AOP 方法?
回答by robertklep
That's what middlewareis for:
这就是中间件的用途:
app.use(function(req, res, next) {
if (!req.headers.authorization) {
return res.status(403).json({ error: 'No credentials sent!' });
}
next();
});
...all your protected routes...
Make sure that the middleware is declared beforethe routes to which the middleware should apply.
确保中间件在应用中间件的路由之前声明。

