Ich habe eine Node Express RESTful API mit jsonwebtoken als Authentifizierungsmethode erstellt. Aber nicht in der Lage, das x-access-token als Header mit angular js zu übergeben.So übergeben Sie JsonWebToken x-access-token durch angular js
meine JWT Token-Authentifizierung Skript ist,
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
});
}
}
});
});
Middleware, die das 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.'
});
}
});
Schließlich Skript der GET-Methode ist,
app.get('/display', function(req, res) {
Item.find({}, function(err, items) {
$http.defaults.headers.common['X-Access-Token']=token;
res.json(items);
});
});
Aber es ist richtig überprüft wird konnte immer nicht authentifiziert werden. Bitte helfen Sie mir, dieses Problem zu lösen. Ich bin hier wirklich festgefahren.
Es wird immer nur die folgende Meldung angezeigt, dass die Authentifizierung fehlgeschlagen ist.
{"success":false,"message":"No token provided."}
Sie, dass vor hat zu suchen und was hast du bekommen? –
@jicks Können Sie bitte Ihre eckige Route zeigen? –