0

I am making a pure NodeJs server and am trying to redirect the user. However, changing the location header doesn't help. In Chrome, I see that the response header has location and the code is 201 (I tried it with other codes, too), but Chrome (and neither does Edge) doesn't redirect. What am I doing wrong? Here is how I am trying to redirect (I made it as a server so it is easier to test for you):

const http = require("http"); function requestHandler(req, res) { res.writeHead(201, { "Location": "/cats" }); } function listeningHandler() {} const app = http.createServer(requestHandler); app.listen(5000, listeningHandler); 

1 Answer 1

1

You should be using a 3XX code to let the browser know a redirect is required. You are probably after a 302.

Have a look at the HTTP status codes on this page for some more information.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages

Sign up to request clarification or add additional context in comments.

3 Comments

It worked with 301, but shouldn't it also work with other codes? developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location says it should also work with 201 and all 3xx codes.
Edit: Thank you. I think I confused the location header's use in 201 and 3xx codes and probably didn't restart the server for the other codes I tested which were 3xx so I thought 3xx codes didn't work too. I don't know how I could have missed to do that but it seems only reasonable because I'm pretty sure I tried it with 302 and 303 and it didn't work when it works now.
That's great @asharpharp ! Don't forget to mark the answer as accepted if it works for you so others who find this question know.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.