Authenticating the request header with Express

二次信任 提交于 2019-12-21 03:29:26

问题


I want to verify that all our get requests have a specific token in their authentication header.

I can add this to our get endpoints:

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?


回答1:


That's what middleware is 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 before the routes to which the middleware should apply.



来源:https://stackoverflow.com/questions/46094417/authenticating-the-request-header-with-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!