简体   繁体   English

将用户从node.js发送到新网址

[英]Send user to new url from node.js

I'm working on a Node.js app. 我正在开发Node.js应用程序。 When a user hits the main url, a database call will be made. 当用户点击主URL时,将进行数据库调用。 This database call returns a URL path. 该数据库调用返回URL路径。 I'm trying to understand how to send the user to that new URL from my Node app. 我试图了解如何将用户从我的Node应用程序发送到该新URL。 That URL is local to the app itself. 该网址是应用本身的本地网址。 Everything I see involves a 301. I'm not sure if that what I really want though. 我看到的所有内容都包含一个301。我不确定那是否是我真正想要的。 Currently, my code looks like this: 目前,我的代码如下所示:

getUserUrl: function (req, res) {
  var url = getNewUrl();
  res.status(200).send();
}

This only confirms the request to getUserUrl was ok. 这仅确认对getUserUrl的请求正常。 However, it doesn't actually send the user to url. 但是,它实际上不会将用户发送到url。 How do I redirect the user to url? 如何将用户重定向到url?

THank you! 谢谢!

I don't know why you say a 301 isn't what you want, because that is definitely one of the options you have available to you. 我不知道您为什么说301不是您想要的,因为这绝对是您可以使用的选项之一。

Typically, a 301 status code is used for a permanent redirect. 通常, 301状态代码用于永久重定向。 That is, a request for a certain URL will be considered to always redirect to where you send that user, and browsers and proxies can cache this redirection indefinitely. 也就是说,对某个URL的请求将被视为始终重定向到您向该用户发送的位置,并且浏览器和代理可以无限期地缓存此重定向。

A 302 status code is a temporary redirect. 302状态码是一个临时重定向。 Subsequent requests for the same URL will come to your server (as long as you don't enable caching for it), allowing you to continue to redirect or not. 随后对同一URL的请求将到达您的服务器(只要您不为其启用缓存),就可以继续进行重定向或不进行重定向。

In either case, you need the status code along with a Location: header to tell the user agent where to go. 无论哪种情况,您都需要状态码和Location:标头来告诉用户代理要去哪里。

res.setHeader('Location', 'http://example.com');
res.statusCode = 302;
res.end();

These days you can also use 307 and 308 status codes for redirection. 这些天,您还可以使用307和308状态代码进行重定向。 They are more explicitly defined in the RFCs and provide roughly the same functionality as 301 and 302. 它们在RFC中更明确地定义,并提供与301和302大致相同的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM