Chin
Chin

Reputation: 12712

Express js - can't redirect

I am trying to do the following:

from client

var req =  jQuery.post(
  "http://www.example.com:3000"+"/dologin", 
  {"username" : username, "password" : password}).error(function(){
    alert("an error occurred");
  });

in express root

app.post('/dologin',function(req, res) {
  res.redirect('http://bbc.co.uk');
});

result passed back

<p>Moved Temporarily. Redirecting to <a href="http://bbc.co.uk">http://bbc.co.uk</a></p>

Seems that if I do post from jquery the redirect will not work. Does anyone know a way to force it to redirect?

Upvotes: 10

Views: 34521

Answers (4)

KirilStankov
KirilStankov

Reputation: 87

I have come to a similar problem and solved it by checking the type of the request. In my case I use JSON, but it works for other POST requests as well:

                var ajax = req.xhr;
                if(ajax) {
                    res.status(401).json({'msg':'redirect','location':'/login'});
                }
                else {
                    req.method = 'get';
                    res.status(401).redirect('/login');
                    //Or if you prefer plain text
                    //res.status(333).send("Redirect");
                }

This handles both Ajax POST and AJAX and standard GET requests. On the client, in the Ajax respose callback:

$.ajax({
        type: 'POST',
        data: Msg,
        url: '/some/post',
        dataType: 'JSON'
    }).success(function(data, textStatus, req ) {
        if(data.msg==="redirect") window.location = data.location;
        else {...}
    }).error(function(data, textStatus, req) {
         if(req=="Unauthorized") {
            alert("Unauthorized!");
            window.location = "/login";
        } else if (data.responseJSON.msg==="redirect") window.location = data.responseJSON.location;
        else {
           //...
        }
    });

You can actually handle more statuses here, except for 302, which is automatically followed by JQuery and you get as response 200 from the page you wanted to redirect to. So I avoid sending the 302, sending 401 in my case, or any other status, for example 333, which will be handled as error.

Upvotes: 0

Paul S Chapman
Paul S Chapman

Reputation: 832

I'm doing something like this when using OAuth2. I have an link to one of my pages and this in turn redirects to google.

To redirect to another location the following code does the actual redirect

app.get('/GoogleRequestAuthorization.html',function(req,res) {
.
.
.
.

res.writeHead(302, {location: url});
res.end();

});

url being the address you want to redirect to.

The full function is...

Upvotes: 0

Teemu Ikonen
Teemu Ikonen

Reputation: 11929

Browser does not redirect the window on redirect on ajax response. Redirect the browser with javascript.

In server send the new site as content, for example.

res.contentType('application/json');
var data = JSON.stringify('http://site.example.com/')
res.header('Content-Length', data.length);
res.end(data);

In client

var req =  jQuery.post(
   "http://www.mysite.com:3000"+"/dologin", 
    {"username" : username, "password" : password}, 'json').error(function(){
       alert("an error occurred");
    }).success(function(data) {
       window.location = data;
    });

Upvotes: 19

alessioalex
alessioalex

Reputation: 63663

I've actually encountered the same thing when developing an app. It seems Express doesn't redirect if the method is post.

Try:

app.post('/dologin',function(req, res) {
  req.method = 'get'; 
  res.redirect('http://bbc.co.uk'); 
});

Upvotes: 15

Related Questions