Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 989
Anne van Rossum Avatar asked Jul 05 '13 20:07

Anne van Rossum


1 Answers

$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

like image 183
John Tseng Avatar answered Oct 20 '22 01:10

John Tseng