Reputation: 467
I have learnt angularJS for three days,but I have some questions during my study.
well,in the "Run Block":
angular.module("techNodeApp",["ngRoute"]).
run(function($window,$rootScope,$http,$location){
$http({
url:"/api/validate",
method:"GET"
}).success(function(user){
console.log("success");
$rootScope.me=user;
$location.path("/");
}).error(function(data){
console.log("error");
$location.path("/login");
});
$rootScope.logout=function(){
$http({
url:"/api/logout",
method:"GET"
}).success(function(){
console.log("I've logged out");
$rootScope.me=null;
$location.path("/login");
})
}
})
In the server(Node.js):
app.get("/api/validate",function(req,res){
console.log("I can hear you FE");
});
app.get("/ajax/validate",function(req,res){
var _userId=req.session._userId;
if(_userId){
Controllers.findUserById(_userId,function(err,user){
if(err){
res.json(401,{msg:err});
}else{
res.json(user);
}
})
}else{
res.json(401,null);
}
});
The first I enter the website I haven't log in,so I thought when the app start run.It must go to the page of "http://localhost:3000/login".But it went to "http://localhost:3000" and it can't print the string "I can hear you FE" in the cmd.
Upvotes: 0
Views: 45
Reputation: 4189
1) Your node.js
app doesn't respond with a user
when a request is made to /api/validate
. So in your angular
app, when that AJAX request succeeds, user
will be undefined
.
2) When that request succeeds, you set $location.path
to /
. So it will obviously go to localhost:3000/
and not to localhost:3000/api/validate
.
3) $http
makes an AJAX request, it doesn't change the location of browser (URL that browser loads). $location.path
does that.
4) Currently it should actually display I can hear you FE
in node.js
output, unless you have some other problems with your node.js
configuration or unless you forget to bootstrap your angular
app (typically with ng-app
directive in your html).
Upvotes: 1