Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 416
Chin Avatar asked Nov 23 '11 10:11

Chin


2 Answers

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;
    });
like image 85
Teemu Ikonen Avatar answered Oct 26 '22 21:10

Teemu Ikonen


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'); 
});
like image 43
alessioalex Avatar answered Oct 26 '22 22:10

alessioalex