gpt4 book ai didi

angularjs - 如何通过angular js传递JsonWebToken x-access-token

转载 作者:搜寻专家 更新时间:2023-10-31 23:01:44 24 4
gpt4 key购买 nike

我使用 jsonwebtoken 作为身份验证方法创建了一个 Node 表达 RESTful API。但是无法使用 angular js 将 x-access-token 作为 header 传递。

我的 JWT token 认证脚本是,

apps.post('/authenticate', function(req, res) {

// find the item
Item.findOne({
name: req.body.name
}, function(err, item) {

if (err) throw err;

if (!item)
{
res.json({ success: false, message: 'Authentication failed. item not found.' });
}
else if (item)
{

// check if password matches
if (item.password != req.body.password)
{
res.json({ success: false, message: 'Authentication failed. Wrong password.' });
}
else
{

// if item is found and password is right
// create a token
var token = jwt.sign(item, app.get('superSecret'), {
expiresIn: 86400 // expires in 24 hours
});



res.json({
success: true,
message: 'Enjoy your token!',
token: token
});





}

}

});
});

检查 token 是否正确的中间件是,

apps.use(function(req, res, next) {

// check header or url parameters or post parameters for token
var token = req.body.token || req.params.token || req.headers['x-access-token'];

// decode token
if (token)
{

// verifies secret and checks exp
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
if (err)
{
return res.json({ success: false, message: 'Failed to authenticate token.' });
}
else
{
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});

}
else
{

// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});

}

});

最后是 GET 方法脚本,

app.get('/display', function(req, res) {
Item.find({}, function(err, items) {



$http.defaults.headers.common['X-Access-Token']=token;

res.json(items);
});
});

但是总是验证失败。请任何人帮助我解决这个问题。我真的被困在这里了。

它始终只显示以下身份验证失败消息。

{"success":false,"message":"No token provided."}

最佳答案

如果你在你的 Angular Controller 中使用 $http 作为依赖项,那么我猜这会对你有所帮助 -

var token = this.AuthToken.getToken();
$http.get('/api/me', { headers: {'x-access-token': token} });

一旦你上传你的 Angular 代码,我会根据你的代码更改它。

关于angularjs - 如何通过angular js传递JsonWebToken x-access-token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36886593/

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