[英]Is it possible to pass a request header on a link with EJS template? Express/Node.js
I'm a trying to make a route accessible only if you are authenticated with JWT using below middleware but I can't seem to find a way to pass the token in the get request from client side?我正在尝试仅当您使用以下中间件通过 JWT 进行身份验证时才可以访问路由,但我似乎无法找到一种方法来在客户端的获取请求中传递令牌? It works fine on postman and I if using a fetch from client side it won't redirect me to the page I want to go
它在 postman 上工作正常,如果我使用从客户端获取它不会将我重定向到我想要的页面 go
auth.js auth.js
async function (req, res, next) {
const token = req.header('x-auth-token');
if (!token) {
return res.status(401).json({ msg: 'Forbidden' });
}
try {
const decoded = jwt.verify(token, process.env.TOKEN_SECRET);
req.user = decoded.user;
next();
} catch (e) {
return res.status(401).json({ err: 'fail' });
}
};
server side服务器端
router.get('/', auth, function (req, res, next) {
res.render('pages/person');
});
You can simply attach your token
to the headers
in the request and sent it with get
or even 'delete` method.您只需将您的
token
附加到请求中的headers
,然后使用get
或什至“删除”方法发送它。
for example, in the fetch
method you can attach your token in this way in your client side:例如,在
fetch
方法中,您可以在客户端以这种方式附加令牌:
fetch('URL_GOES_HERE', {
method: 'post',
headers: new Headers({
'Authorization': YOUR_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
}),
});
Now, you can retrieve the token in the node app:现在,您可以在节点应用程序中检索令牌:
const token = req.headers.authorization || "";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.