redirecting a page with angular routing after successfully calling an api on express server

僤鯓⒐⒋嵵緔 提交于 2019-12-05 18:28:10

Using successRedirect and failureRedirect in passport will redirect the client to the specified pages, which will prevent your client-side angularJS routing from taking place. The reason you're seeing the user info after logging in is because your client is being redirected to the /success page, rather than actually responding to the original request. The client then fetches the success page with a GET request, and the new GET request is then responded to with the user info.

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

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, passport will respond directly with a 401 error status, with a body of "Unauthorized". Therefore the success state is not required. On the client side, you should use the .error() function to deal with 401 errors, rather than 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 pass back a more specific reason as to why the request was unauthorized (which is not always a good idea), you can use flash messages, and issue another GET request from angular to get a more detailed authorization failure message.

You seem to have a slight impedance mismatch on what the front-end and back-end want to do here. Your AngularJS code expects to make a POST to the API endpoint and get back a 200 (success) along with some JSON data which tells it about the success or failure of the login attempt.

The back-end, thinks it's going to receive a POST and then redirect the caller to a new location. At least that's the way I'm reading it. It's not simply sending back some data with an HTTP response code of 200 or an error code.

I think you want to tweak the back-end code to simply return data to the front-end to get the result you expect.

So far I haven't seen success in making Ajax calls to API redirecting to a page. We have a similar situation where API call may result in redirecting to a error page. We wanted to handle that in the server rather than asking UI (Angular) to do it. But it's just frustrating to see none of the methods of redirect like res.redirect are working. Our scenario is Angular makes a API call through Ajax and API running on Node.js should redirect to a html page.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!