Nodejs : Redirect URL

2019-02-04 16:31发布

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?

5条回答
爷的心禁止访问
2楼-- · 2019-02-04 17:08

Yes it should be full url in setHeader.

  res.statusCode = 302;
  res.setHeader('Location', 'http://' + req.headers['host'] + ('/' !== req.url)? ( '/' + req.url) : '');
  res.end();
查看更多
Evening l夕情丶
3楼-- · 2019-02-04 17:10

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);
};
查看更多
劳资没心,怎么记你
4楼-- · 2019-02-04 17:16

This issue may also depend on the type of request you are handling. A POST request cannot be redirected using the header. For example, a first-time visitor from to your app in FB will most-likely be coming via a "signed request" POST and therefore a redirect will not work.

查看更多
看我几分像从前
5楼-- · 2019-02-04 17:20
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);
    });
查看更多
欢心
6楼-- · 2019-02-04 17:27

What happens if you change it to 307 instead?

查看更多
登录 后发表回答