Home > Back-end >  Express.js route not working every time if redirecting
Express.js route not working every time if redirecting

Time:04-22

I have a really simple express.js server,

app.get("/:var", (req, res) => {
    console.log(req.params.var);
    res.redirect(301, "/");
});

Now on my browser, if I go to the following urls one after another

localhost:127/abc
localhost:127/abc
localhost:127/xyz
localhost:127/abc
localhost:127/xyz
localhost:127/xyz
localhost:127/abc

I get the following output in my server's terminal

abc
xyz

For some reason, if I remove the res.redirect(301, "/"), everything works as expected and I get the following output

abc
abc
xyz
abc
xyz
xyz
abc

Even if I restart the server, I cannot use a value that I had use before the restart. Only if I delete the cache from my browser, can I use that value again just once.

Can someone explain what is going on? I need to keep the redirect and also process the data from the url before redirecting and hopefully not have the client clearing their browser cache every time they want to use the site.

CodePudding user response:

Here it said: A 301 response is cacheable by default; i.e., unless otherwise indicated by the method definition or explicit cache controls - reference: https://httpwg.org/specs/rfc7231.html#status.301

So your seeing behavior is correct, you have to clear cache in browsers to see the new response.

The statement above also suggests the solution, you can set the cache header to tell browsers not to cache the response. Something like:

res.set("cache-control","no-store")
  • Related