Skip to content
Advertisement

res.redirect() not working properly in express JS

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.

Advertisement

Answer

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 Google Apps Script return 405 for POST request.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement