I’m trying to get redirect url using fetch without following it but i don’t figure out how to do it.
I created a simple http server using express
to illustrate what i have done :
const express = require("express");
const app = express();
app
.get("/", (_, res) => res.redirect("/redirect"))
.get("/redirect", (_, res) => res.send("Redirect page"));
const port = 5000;
app.listen(port, () => console.log(`Server runs on http://localhost:${port}`));
In the browser, if i use the following code, i can get the redirect url :
fetch("http://localhost:5000").then((res) =>
console.log(`Redirect url : ${res.url}`)
);
However, this code follows the redirect url and connects on it that i want to avoid. So i try this another code :
fetch("http://localhost:5000", {redirect: "manual"}).then((res) =>
console.log(`Original url : ${res.url}`)
);
The redirect url is not followed as expected, however the res.url
is not the redirect url. I think it is logic, so i was thinking my redirect url is in the header location
but no. The following code outputs null
as value of location
:
fetch("http://localhost:5000", { redirect: "manual" }).then((res) => {
console.log(res.headers.get("location"));
console.log(res.headers.get("Location"));
});
Thank you in advance for your help.