Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs : Redirect URL

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?

like image 847
Adam Halasz Avatar asked Jun 04 '11 02:06

Adam Halasz


People also ask

What is redirect in node JS?

redirect() function lets you redirect the user to a different URL by sending an HTTP response with status 302. The HTTP client (browser, Axios, etc.) will then "follow" the redirect and send an HTTP request to the new URL as shown below. const app = require('express')(); // The `res.

How do I redirect a HTML page to another HTML page?

To redirect one HTML page to another page, you need to add a <meta> tag inside the <head> section of the old HTML page. The <head> section of an HTML document contains metadata that is useful for the browser, but invisible to users viewing the page.

How do I use response redirect?

Response. Redirect sends an HTTP request to the browser, then the browser sends that request to the web server, then the web server delivers a response to the web browser. For example, suppose you are on the web page "UserRegister. aspx" page and it has a button that redirects you to the "UserDetail.


2 Answers

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);
};
like image 100
Geoff Chappell Avatar answered Sep 20 '22 15:09

Geoff Chappell


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);
    });
like image 42
Brad Avatar answered Sep 18 '22 15:09

Brad