Nodejs : Redirect URL

24,446

Solution 1

Looks like express does it pretty much the way you have. From what I can see the differences are that they push some body content and use an absolute url.

See the express response.redirect method:

https://github.com/visionmedia/express/blob/master/lib/response.js#L335

// Support text/{plain,html} by default
  if (req.accepts('html')) {
    body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';
    this.header('Content-Type', 'text/html');
  } else {
    body = http.STATUS_CODES[status] + '. Redirecting to ' + url;
    this.header('Content-Type', 'text/plain');
  }

  // Respond
  this.statusCode = status;
  this.header('Location', url);
  this.end(body);
};

Solution 2

server = http.createServer(
    function(req, res)
    {
        url ="http://www.google.com";
        body = "Goodbye cruel localhost";
        res.writeHead(301, {
             'Location': url,
             'Content-Length': body.length,
             'Content-Type': 'text/plain' });

        res.end(body);
    });

Solution 3

Yes it should be full url in setHeader.

  res.statusCode = 302;
  res.setHeader('Location', 'http://' + req.headers['host'] + ('/' !== req.url)? ( '/' + req.url) : '');
  res.end();

Solution 4

What happens if you change it to 307 instead?

Share:
24,446
Adam Halasz
Author by

Adam Halasz

Hi, I made 37 open source node.js projects with +147 million downloads. Created the backend system for Hungary's biggest humor network serving 4.5 million unique monthly visitors with a server cost less than $200/month. Successfully failed with several startups before I turned 20. Making money with tech since I'm 15. Wrote my first HTML page when I was 11. Hacked our first PC when I was 4. Lived in 7 countries in the last 4 years. aimform.com - My company adamhalasz.com - My personal website diet.js - Tiny, fast and modular node.js web framework

Updated on July 17, 2022

Comments

  • Adam Halasz
    Adam Halasz almost 2 years

    I'm trying to redirect the url of my app in node.js in this way:

    // response comes from the http server
    response.statusCode = 302;
    response.setHeader("Location", "/page");
    response.end();
    

    But the current page is mixed with the new one, it looks strange :| My solution looked totally logical, I don't really know why this happens, but if I reload the page after the redirection it works.

    Anyway what's the proper way to do HTTP redirects in node?

  • jcolebrand
    jcolebrand almost 13 years
    @CIRK I changed my answer then.