0

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.

1 Answer 1

1

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 angularapp (typically with ng-app directive in your html).

Sign up to request clarification or add additional context in comments.

2 Comments

I just have edit my node.js code. when I get to the page /api/validate ,I think it's must go to the page of /login. But it doesn't work
I guess you are really confused about AJAX requests made with $http, request paths that node.js handle, and $location.path. Instead of trying to hack through it to make it work, try to understand how it works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.