0
我創建令牌在登錄時使用的是Node.js:如何飲用基於令牌的節點API中的角JS
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")
}
})
})
});
我現在想顯示用戶儀表盤頁面/dashboard
路線,我做的事情如下圖所示:
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;
}
};
在postman
時,我打/dashboard
API其工作良好。並打印輸出success:true, msg:'Welcome in the Area Admin
; 但是,當在角js我消耗這個API然後在節點控制檯輸出是null
。 下面是我的角度功能消耗API
app.controller('dashboardCtrl', function($scope, $http, $location, $routeParams){
$http.get('/api/dashboard').success(function(res){
$scope.result=res;
})
})
我想知道如何在角消費令牌基於路由。我知道上面給出的角度函數是不正確的。請讓我知道正確的代碼。
感謝
記號沒有定義 –
沒有,'token'是從你的'$ http.put( '/ API /登錄')'的反應。我只是抽象出了那部分,因爲我假設你已經這樣做了,並將響應保存在'token'變量中。 – willie17
是我沒有...喜歡作爲 $ scope.login =函數(){ \t \t $ http.put( '/ API /登錄',$ scope.new)。然後(函數(響應){ \t \t \t $ cookieStore.put( '令牌',response.data.token); \t \t \t $ cookieStore.put( 'currentUser',$ scope.new.email); \t \t \t $ rootScope.token =響應。 data.token; \t \t \t $ rootScope.currentUser = $ scope.new.email; \t $ location.p ATH( '/儀表盤'); \t $ scope.loggindata = response; ('電子郵件和密碼不正確'); \t \t}); \t} –