Page redirection with angular routing after successful api call on express server

In a single page app using angular routing, how can I redirect the page after the api call. In my case, I want to redirect the user to the profile page after they have called the login api. Now, I thought it would work, but it doesn't.

On the client main.js. I have angular routing setup set

app.config(function($routeProvider){   $routeProvider
//the home page display
.when('/', {
  templateUrl: 'main.html',
  controller: 'mainController'
})

.when('/login', {
  templateUrl: 'login.html',
  controller: 'loginController'
})

.when('/signUp', {
  templateUrl: 'signUp.html',
  controller: 'signUpController'
})

.when('/profile', {
  templateUrl: 'profile.html',
  //controller: 'mainController'
}); });

      

and from my controller i call the / login post api

app.controller('authController', function($scope, $http, $rootScope, $location){   
  $scope.user = {username: '', password: ''};   
  $scope.error_message = '';

  $scope.login = function(){
    $http.post('/login', $scope.user).success(function(data){
      if(data.state == 'success'){
        //set username authenticated property to true after successful log in
        //I am only pasting some of my code here, more logic before controller
        $rootScope.authenticated = true;
        $rootScope.current_user = "james";
        $location.path('/profile');
      }
      else{
        $scope.error_message = data.message;
      }
    });   
  }; 
});

      

and here is my api login

router.post('/login', passport.authenticate('local-login', {
        successRedirect : '/success', // redirect to the secure profile section
        failureRedirect : '/failure', // redirect back to the signup page if there is an error
        failureFlash : true // allow flash messages
    }));

      

and when it succeeds, it calls success, which sends back the data, which should trigger a callback to $ http.post and redirect the page via $ location.path ('/ profile') ;. However, the callback is not called and my page displays the user information from res.send

//sends successful login state back to angular
    router.get('/success', function(req, res){
        res.send({state: 'success', user: req.user ? req.user : null});
    });

      

Am I on the right track? I am just following the microsoft tutorial https://www.microsoftvirtualacademy.com/en-us/training-courses/mean-stack-jump-start-8442 but their completed github page doesn't even work so I can't debug this my problem.

+3


source to share


3 answers


Using successRedirect

and failureRedirect

in passport will redirect the client to the specified pages, which will prevent your client side routing. The reason you see user information after logging in is because your client is redirected to the page /success

instead of responding to the original request. The client then fetches the success page with a GET request and then a new GET request responds with information about the user.

I would suggest leaving node.js redirects when using AngularJS, as you probably want to handle the client side redirects:

router.post('/login', passport.authenticate('local-login'), function(req, res){
    res.send(req.user);
});

      



The inline function will never execute if the user is not authenticated. Instead, the passport will respond directly with a 401 error status, with the body "Unauthorized". Therefore, success

no state is required. On the client side, you should use a function .error()

to resolve 401 errors instead of checking your state variable:

$http.post('/login', $scope.user).success(function(user){
    $rootScope.authenticated = true;
    $rootScope.current_user = "james";
    $location.path('/profile');
  })
 .error(function(err){
    $scope.error_message = err;
  });

      

If you want to convey a more specific reason why the request was unauthorized (which is not always useful), you can use flash messages and issue another GET request from angular to get more detailed authorization error message.

+3


source


You seem to have a slight impedance mismatch on what front-end and back-end want to do here. Your AngularJS code expects to do a POST to the API endpoint and get 200 (success) along with some JSON data that reports a successful or unsuccessful login attempt.

In the background it is supposed to receive a POST and then redirect the caller to a new location. At least the way I read it. It's not just sending some data with HTTP 200 response code or error code.



I think you want to set up external code to just return data to the interface in order to get the expected result.

0


source


So far, I have not seen success in making Ajax calls to redirect the API to the page. We have a similar situation where an API call can lead to a redirect to an error page. We wanted to handle this on the server, not ask the UI (Angular) to do it. But it's just frustrating that none of the redirect methods like res.redirect work. Our Angular script makes an API call via Ajax and the API running on Node.js should redirect to the html page.

0


source







All Articles