Reputation: 804
I am creating token at login time with node.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")
}
})
})
});
now I am trying to show user dashboard page with /dashboard
route and I am doing something like below:
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
when I hit /dashboard
api its working good. and printing the output success:true, msg:'Welcome in the Area Admin
;
But when in angular js I am consuming this api then output in node console is null
.
Below is my angular function to consume api
app.controller('dashboardCtrl', function($scope, $http, $location, $routeParams){
$http.get('/api/dashboard').success(function(res){
$scope.result=res;
})
})
I want to know how to consume token based route in angular. I know above given angular function is not right. Please let me know the right code.
Thanks
Upvotes: 0
Views: 89
Reputation: 901
You didn't set the header for the $http.get()
. Here is how you should do:
$http.get('/api/dashboard', {
headers: {
// Set header for the request here
authorization: token
}
})
.success(function(res) {
// Success
});
Upvotes: 1