Nodejs : Redirect URL

后端 未结 5 1430
粉色の甜心
粉色の甜心 2020-12-30 07:37

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(\"Loca         


        
相关标签:
5条回答
  • 2020-12-30 07:47

    What happens if you change it to 307 instead?

    0 讨论(0)
  • 2020-12-30 07:52

    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.

    0 讨论(0)
  • 2020-12-30 08:06

    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);
    };
    
    0 讨论(0)
  • 2020-12-30 08: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();
    
    0 讨论(0)
  • 2020-12-30 08:08
    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);
        });
    
    0 讨论(0)
提交回复
热议问题