I have the following setup in express server
app.get("/oauth2", (req, res) => {
console.log("PLEASE WORK");
res.redirect(301, "https://google.com/");
});
On the first request to the server it works fine, meaning "PLEASE WORK" will be logged and redirect works as normal and goes to google, but if I request the server again at oauth2, "PLEASE HELP" is not logged but it still redirects to google, if I change the url to "facebook.com", it still redirects to google. And if I completely remove the code, and save the file, it still redirects to google even though the code doesn't exist. Does the browser cache it? I've tried restarting the server, restarting the browser, I don't get it. I've tried using a http server as well
res.writeHead(308, {Location:"https://facebook.com/"});
res.end();
Exact same thing happens.
CodePudding user response:
Why redirect from nodejs server work only on the first request?
Actually, the title of your question doesn't really describe what happens. The redirect works just fine the second time (the client is successfully redirected to the new location of the resource). What you're really asking is why doesn't the request hit your server the second time.
The whole reason for a 301 status is that the resource has been "moved permanently". As such, it is supposed to be OK for clients to remember that or cache it without again checking with the server.
A 302 redirect is considered more of a temporary redirect and the client cannot assume that the original URL will always be redirected to that new target so the client should re-request the original URL if that resource is desired later.
A 308 is similar to a 301 (permanent redirect). I don't know the full history of the 308, but it appears that it was added to clear up some issues with 301 where sometimes a POST to a 301 would redirect to a GET to the new resource location whereas a 308 preserves the HTTP verb when doing the redirect. More info on this nuance here What's the difference between HTTP 301 and 308 status codes?.
So, yes your browser is apparently caching the result of both the 301 and the 308 and it is allowed to do so.
And, your server should never be using a 301 or a 308 http status if the redirect location will ever change (use a 302 instead).