使用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屋!
查看全文