如何用JavaScript原生Fetch获取重定向URL且不跟随跳转?
解决Fetch获取重定向URL但不跟随跳转的问题
你遇到的Location头返回null的核心原因是:跨域请求时,浏览器默认只会暴露少数CORS安全的响应头(比如Content-Type),Location不在这个列表里,所以前端无法直接获取。
步骤1:修改Express服务器,配置CORS并暴露Location头
先安装cors中间件:
npm install cors
然后修改服务器代码,添加CORS配置,明确暴露Location头:
const express = require("express"); const cors = require("cors"); const app = express(); // 配置CORS,允许跨域请求并暴露Location头 app.use(cors({ exposedHeaders: ["Location"] })); 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}`));
步骤2:前端Fetch获取重定向URL
现在使用redirect: "manual"发起请求,就能拿到Location头了。另外注意Location可能是相对路径,需要结合原请求的URL拼接成完整地址:
fetch("http://localhost:5000", { redirect: "manual" }) .then(res => { if (res.status >= 300 && res.status < 400) { const location = res.headers.get("Location"); // 拼接完整URL:如果是相对路径,用原URL的origin拼接 const fullRedirectUrl = new URL(location, res.url).href; console.log(`重定向URL:${fullRedirectUrl}`); } });
这样就能在不跟随重定向的前提下,获取到完整的重定向目标URL了。
内容的提问来源于stack exchange,提问作者RAZAFINARIVO Hanania
相关产品推荐
相关产品推荐

