I Token mit node.js bei der Anmeldung erschaffe:Wie Token
apiRoutes.put('/login', function(req, res, next){
User.findOne({email:req.body.email}, function(err, user){
bcrypt.compare(req.body.password, user.password, function(err, result){
if(result){
var token=jwt.encode(user,config.secret);
return res.json({success: true, token:'JWT' +token});
}else{
return res.json("Incorrect Email and Password")
}
})
})
});
jetzt versuche ich Benutzer Dashboardseite mit /dashboard
Weg zu zeigen, und ich etwas tue unten wie:
apiRoutes.get('/dashboard',function(req, res) {
var token=getToken(req.headers);
if(token){
var decode=jwt.decode(token, config.secret);
console.log(decode);
User.findOne({name:decode.name}, function(err, user){
if(err){res.json(err)}
if(!user){
return res.status(403).send({success:false, msg:'Authentication Failed'})
}else{
res.json({success:true, msg:'Welcome in the Area ' +user.name+'!' })
}
})
}else{
return res.status(403).send({success:false, msg:'No Token Found'})
}
});
getToken = function (head) {
if (head && head.authorization) {
var parted = head.authorization.split(' ');
if (parted.length == 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};
In postman
wenn ich traf /dashboard
api seine Arbeit gut. und Drucken der Ausgabe success:true, msg:'Welcome in the Area Admin
; Aber wenn in angular js ich diese API konsumiere dann ist Ausgabe in Node-Konsole null
. Unten ist meine Winkelfunktion api
app.controller('dashboardCtrl', function($scope, $http, $location, $routeParams){
$http.get('/api/dashboard').success(function(res){
$scope.result=res;
})
})
ich wissen will, zu konsumieren, wie Token in Winkel basierend Route zu konsumieren. Ich weiß oben angegebene Winkelfunktion ist nicht richtig. Bitte lassen Sie mich den richtigen Code wissen.
Dank
Token ist nicht definiert –
Nein, 'token' ist aus der Antwort von Ihrem' $ http.put ('/ api/login') '. Ich habe diesen Teil nur abstrahiert, weil ich davon ausgegangen bin, dass du das bereits getan hast und rette die Antwort in der 'token'-Variablen. – willie17
ja, ich habe ... wie als scope.login $ = function() { \t \t $ http.put ('/ api/login', $ scope.new) .then (function (Antwort) { \t \t \t $ cookieStore.put ('token', response.data.token); \t \t \t $ cookieStore.put ('current', $ scope.new.email); \t \t \t $ rootScope.token = Antwort. data.token; \t \t \t $ rootScope.currentUser = $ scope.new.email; \t $ location.p ath ('/ Armaturenbrett'); \t $ scope.loggindata = Antwort; \t \t} function (err) { \t \t \t alert ('Falsche E-Mail und Passwort'); \t \t}); \t} –