Home > Enterprise >  Redirecting a Node.js/Express request to another server
Redirecting a Node.js/Express request to another server

Time:10-04

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?

CodePudding user response:

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

CodePudding user response:

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');
});
  • Related