gpt4 book ai didi

javascript - 在 Node request.headers 中设置权限

转载 作者:搜寻专家 更新时间:2023-11-01 00:17:27 28 4
gpt4 key购买 nike

我正在尝试向客户端发送 Passport-Local 登录请求以供 Satellizer 分析,我希望服务器端发送授权 token 的请求。不幸的是,request.headers 中没有关键的authorization:

{ host: 'localhost:3000',
connection: 'keep-alive',
'cache-control': 'max-age=0',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' }

登录函数重定向到这里,这是调用 ensureAuthenticated() 的地方。

app.get('/main', ensureAuthenticated, function(req, res, next){
res.render('main.ejs', { token: createSendToken(req.user, config.secret), id: req.user._id, username: req.user.username, authorization: req.user.authorization });
});

ensureAuthenticated() 然后分析登录请求并确保 token 匹配:

function ensureAuthenticated(req, res, next) {

if (!req.headers.authorization) {
return res.status(401).send({ message: 'Please make sure your request has an Authorization header' });
}
var token = req.headers.authorization.split(' ')[1];

var payload = null;
try {
payload = jwt.decode(token, config.token_secret);
}
catch (err) {
return res.status(401).send({ message: err.message });
}

if (payload.exp <= moment().unix()) {
return res.status(401).send({ message: 'Token has expired' });
}
req.user = payload.sub;
next();
}

然后重定向并显示消息

{ message: 'Please make sure your request has an Authorization header' }

如何为 request.headers 设置授权 key ?

最佳答案

要在请求中设置一个新的 header 字段,只需直接访问它,因为 header 对象看起来像一个普通的哈希表。

request.headers.authorization = value;

关于javascript - 在 Node request.headers 中设置权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35315528/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com