Nodejs:重定向 URL [英] Nodejs : Redirect URL

查看:50
本文介绍了Nodejs:重定向 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以这种方式在 node.js 中重定向我的应用程序的 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.

无论如何,在节点中进行 HTTP 重定向的正确方法是什么?

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

推荐答案

看起来 express 和你的方式差不多.从我所看到的不同之处在于它们推送一些正文内容并使用绝对网址.

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.

查看 express response.redirect 方法:

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);
};

这篇关于Nodejs:重定向 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆