简体   繁体   中英

Send user to new url from node.js

I'm working on a Node.js app. When a user hits the main url, a database call will be made. This database call returns a URL path. I'm trying to understand how to send the user to that new URL from my Node app. 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. 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. However, it doesn't actually send the user to url. How do I redirect the user to 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.

Typically, a 301 status code is used for a permanent redirect. 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.

A 302 status code is a temporary redirect. 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.

In either case, you need the status code along with a Location: header to tell the user agent where to go.

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

These days you can also use 307 and 308 status codes for redirection. They are more explicitly defined in the RFCs and provide roughly the same functionality as 301 and 302.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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