使用 Express 验证请求头 [英] Authenticating the request header with Express
本文介绍了使用 Express 验证请求头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想验证我们所有的 get 请求在其身份验证标头中是否都有特定的令牌.
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:
app.get('/events/country', function(req, res) {
if (!req.headers.authorization) {
return res.json({ error: 'No credentials sent!' });
}
在 NodeJS/Express 中有没有更好的方法来处理这个而不改变每个端点?类似于过滤前/AOP 方法?
Is there any better way to handle this in NodeJS/Express without changing every endpoint? something like a before-filter/AOP approach?
推荐答案
这就是 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...
确保中间件在应用中间件的路由之前声明.
Make sure that the middleware is declared before the routes to which the middleware should apply.
这篇关于使用 Express 验证请求头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文