Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Express js - can't redirect

Express js - can't redirect

Problem

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

Moved Temporarily. Redirecting to http://bbc.co.uk

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

Problem courtesy of: Chin

Solution

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;
    });
Solution courtesy of: Teemu Ikonen

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Express js - can't redirect

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×