如果不包含特定的 header,如何限制对 url 的访问
How to restrict access to a url if it does not contain a particular header
我正在实现一个 API,它将被不同的用户调用,我希望通过一个名为“租户”的 header 提供用户 ID,否则如果没有提供错误应该抛出消息。
if (! request.get('Tenant')) {
return res.status(403).json({ error: 'No tenant header sent!' });
}
next();
}, router);
我试过上面的代码,但当租户 header 没有作为请求的一部分发送时,它没有限制访问。
获取 headers 并查找其中的值
let headers = JSON.stringify(req.headers);
headers 值会像
{
"host":"localhost:8081",
"connection":"keep-alive",
"cache-control":"max-age=0",
"accept-encoding":"gzip, deflate, sdch",
"accept-language":"en-US,en;q=0.8,et;q=0.6"
}
for(let x in headers) {
if(x['headers'] !== 'tenant'){
return res.status(403).json({ error: 'No tenant information found!' });
}else{
res.redirect(301, '/otherEndpoint')
or
res.status(301).location('/otherEndpoint')
}
}
req.get('tenant');
也适用于 express 版本 4 及更高版本
或者您也可以使用req.header('tenant')
直接查询
我正在实现一个 API,它将被不同的用户调用,我希望通过一个名为“租户”的 header 提供用户 ID,否则如果没有提供错误应该抛出消息。
if (! request.get('Tenant')) {
return res.status(403).json({ error: 'No tenant header sent!' });
}
next();
}, router);
我试过上面的代码,但当租户 header 没有作为请求的一部分发送时,它没有限制访问。
获取 headers 并查找其中的值
let headers = JSON.stringify(req.headers);
headers 值会像
{
"host":"localhost:8081",
"connection":"keep-alive",
"cache-control":"max-age=0",
"accept-encoding":"gzip, deflate, sdch",
"accept-language":"en-US,en;q=0.8,et;q=0.6"
}
for(let x in headers) {
if(x['headers'] !== 'tenant'){
return res.status(403).json({ error: 'No tenant information found!' });
}else{
res.redirect(301, '/otherEndpoint')
or
res.status(301).location('/otherEndpoint')
}
}
req.get('tenant');
也适用于 express 版本 4 及更高版本
或者您也可以使用req.header('tenant')
直接查询