Home > other >  res.redirect() not working properly in express JS
res.redirect() not working properly in express JS

Time:12-27

I've been working on creating an API for a blockchain I've made.

Everything was going fine, until I updated Node and Windows...

====== ISSUE ====== After performing a POST request, I cannot redirect to a GET page anymore. (Using Postman only no front end yet).

For some reason, it was working fine and now I can't do it in a simple test file even.

I've attached the simple express test file below (which duplicates my problem).

const express = require("express");
const app = express();

app.get("/", (req, res) => {
  res.send("Hello World from GET!");
});

// BELOW IS THE WAY I'VE WORKED AROUND IT FOR NOW
// app.post("/", (req, res) => {
//   res.send("Hello World from POST!");
// });

app.post("/me", function (req, res) {
  res.redirect("/");  // ISSUE HAPPENS HERE
});

var server = app.listen(8081, () => {
  var port = server.address().port;
  console.log(`Example app listening at http://localhost:${port}`);
});

Using PostMan, now whenever I try to redirect after app.post("/me"), it will return a 404 error shown below...

<body>
    <pre>Cannot POST /</pre>
</body>

I found out if I add a POST method to the "/" route (commented out above), it will work correctly.

Why didn't I have to do this before??? Did I break my computer? lol

I have tried uninstalling Node v19 and reinstalling Node v16. (no change)

I uninstalled the Windows updates that I did when restarting for Node v19 installation.

CodePudding user response:

Your browser makes a POST / request after redirection, which your app does not accept, it expects a GET / request instead.

Whether a redirection after a POST request leads to a GET request or another POST request depends on the HTTP status (between 301 and 308) as well as on the browser. Perhaps the Windows update changed the default behavior of your browser?

To avoid any ambiguity, you should use

app.post("/me", function (req, res) {
  res.redirect(303, "/");
});

See also Changing Settings

I deactivated "Follow original HTTP Method" in PostMan request settings (near body and headers).

This solved my problem. PostMan was executing another POST request on my redirect, instead of a GET.

Following the link Heiko provided above, and another link on that page about changing PostMan settings, I was able to disable the "Follow original HTTP Method" which will "Redirect with the original HTTP method instead of the default behavior of redirecting with GET" while it is activated.

It appears this is a per request change in PostMan however.

Not sure exactly what caused this to happen, but it works!

  • Related