How to follow a redirect in http.get in AngularJS?

ぐ巨炮叔叔 提交于 2019-12-18 11:56:29

问题


I am working on a website for coaches to help people have healthier lives by using social media. On the moment I am working on access to Twitter through OAuth in a ExpressJS server with AngularJS in the frontend.

From the website of AngularJS:

A response status code between 200 and 299 is considered a success status and will result in the success callback being called. Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning that the error callback will not be called for such responses.

The full code of my server can be found in web.js and twitter.js on github, but this is the caller:

function LoginCtrl($scope, $http, $location) {
  $scope.welcome = 'Sign in with Twitter';
  $http.defaults.useXDomain = true;    
  $scope.submit = function() {    
    $http({method: 'GET', url: '/sessions/connect'}).
    success(function(data, status) {
        $scope.welcome = data;
    });
  };
}

And this is the callee in web.js:

app.get('/sessions/connect', function(req, res){
  consumer().getOAuthRequestToken(function(error, oauthToken, oauthTokenSecret, results){
    if (error) {
      res.send("Error getting OAuth request token : " + sys.inspect(error), 500);
    } else {  
      req.session.oauthRequestToken = oauthToken;
      req.session.oauthRequestTokenSecret = oauthTokenSecret;
      res.redirect("https://api.twitter.com/oauth/authorize?oauth_token="+req.session.oauthRequestToken);      
    }
  });
});

If I check with tcpdump (sorry I'm old-fashioned) I see:

Connection:.keep-alive....Moved.Temporarily..Redirecting.to.https://api.twitter.com/oauth/authorize?oauth_token=***

This is really nice of course, and indeed happens when I go to this server /sessions/connect manually in the browser. However, with AngularJS my browser screen is not actually redirected. Why not?


回答1:


$http goes and gets the contents of the page for you. However, it gives you the results back in the promise. It doesn't change your page at all unless you ask it to. In your then handler, you can do something to redirect your page. There's an example of how you can do that here: Handle an express redirect from Angular POST



来源:https://stackoverflow.com/questions/17496452/how-to-follow-a-redirect-in-http-get-in-angularjs

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