0

I got a situation where I need to redirect an HTTP request made to server X to another server Y,

with all of the requests' headers, params, body etc.

I tried:

app.post('/redirect-source', (req, res, next) => {
  res.redirect(301, 'http://localhost:4000/redirect-target');
});

But the response I get when reaching this route is:

{"message":"Not Found"}

Although the server and route i'm redirecting to are live and I get an ok response when reaching it directly.

What am I missing?

edit: I noticed that the target route works on Postman and not from the browser, my guess is because it's a POST request. How can I configure the redirect to pass as POST/specific type?

flow24
  • 793
  • 2
  • 5
  • 17
  • Can you provide a bit more context on what the user experience supposed to be? Are you trying to forward POST request data to a different location? Or do you want your user to be directed after their request is processed? See https://en.wikipedia.org/wiki/Post/Redirect/Get for the latter. – Artyom Neustroev Oct 02 '22 at 18:16
  • 1
    *with all of the requests' headers, params, body* so proxy then? See https://stackoverflow.com/questions/20351637/how-to-create-a-simple-http-proxy-in-node-js – Lawrence Cherone Oct 02 '22 at 18:20
  • @ArtyomNeustroev By some criteria. I need to decide if a request will be processed in another server. if it does, i need to redirect it with the params etc – flow24 Oct 02 '22 at 18:31
  • @LawrenceCherone is proxy the only option? can't i just redirect a POST request as a whole? – flow24 Oct 02 '22 at 18:47

2 Answers2

0

Try to change the statusCode to 308.

Take a look at this https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/301

Use the 301 code only as a response for GET or HEAD methods and use the 308 Permanent Redirect for POST methods instead, as the method change is explicitly prohibited with this status.

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

0

It turned out that status code 307 is the one that works for POST requests too. Like so:

app.post('/redirect-source', (req, res, next) => {
  res.redirect(307, 'http://localhost:4000/redirect-target');
});
flow24
  • 793
  • 2
  • 5
  • 17