使用 axios 重定向后如何获取着陆页 URL

Nic*_*net 8 node.js axios

使用 NodeJS,如果我使用带有 maxRedirects = 5 的 axios,如果我输入的 URL 将被重定向到另一个 URL,我如何从最终登录页面获取该 URL?在 HTTP 标头中,当有 HTTP 200 代码时,着陆页没有标头字段。

示例:如果我使用:

axios.get('http://stackoverflow.com/',config)
.then(function(response) { console.log(response);}
Run Code Online (Sandbox Code Playgroud)

axios 会自动重定向到https://stackoverflow.com。那么,如何获得最终的 URL 值“ https://stackoverflow.com ”?

我应该在返回的对象“响应”中进行调查并从域和 URI 重新创建完整的 url?

MrF*_*bio 19

我通过以下方式解决了这个问题:

response.request.res.responseUrl
Run Code Online (Sandbox Code Playgroud)

尼古拉斯的回答未能获得端口(如localhost:8080

  • 谢谢,我想自从我发布最初的回复并更新它以来,axios 已经更新了。 (3认同)

Nic*_*net 14

这是我在 NodeJS 上的快速而肮脏的解决方案。起始 URL 是http://www.stackoverflow.com/questions/47444251/how-to-get-the-landing-page-url-after-redirections-using-axios,最终登陆 URL 是 /sf/ask/3321097601/请找到下面的技巧来获取登陆 URL。

axios.get('http://www.stackoverflow.com/questions/47444251/how-to-get-the-landing-page-url-after-redirections-using-axios').then(function(response) {
      console.log(response.request.res.responseUrl);
     }).catch(function(no200){
      console.error("404, 400, and other events");
     
    });
Run Code Online (Sandbox Code Playgroud)

response.request.res.responseURL 是 axios 返回的 JSON 对象中的正确字段。如果您从浏览器运行 axios,请使用 console.log(response.request.responseURL);

  • 我猜这仅在从 Node 使用时才有效,而在浏览器中无效? (2认同)