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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:29:00  来源:igfitidea点击:

Authenticating the request header with Express

node.jsexpressjwtaopaccess-token

提问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.

确保中间件在应用中间件的路由之前声明。