如何在使用axios重定向后获取着陆页网址

时间:2017-11-22 21:38:45

标签: 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);}

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

我应该调查返回的对象"响应"并从域和URI重新创建完整的URL?

2 个答案:

答案 0 :(得分:3)

这是我快速而肮脏的解决方案。起始网址为http://www.stackoverflow.com/questions/47444251/how-to-get-the-landing-page-url-after-redirections-using-axios,最终着陆网址为 https://stackoverflow.com/questions/47444251/how-to-get-the-landing-page-url-after-redirections-using-axios请在下面找到获取着陆网址的技巧。

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.req.agent.protocol+"//"+response.request.res.connection._host+response.request.path);
     }).catch(function(no200){
      console.error("404, 400, and other events");
     console.log(no200.request.res.req.agent.protocol+"//"+no200.request.res.connection._host+no200.request.path);
    });

我从axios返回的对象中获取了正确的字段(协议,根域,uri),以重新创建登录页面的完整URL。

答案 1 :(得分:3)

我通过以下方式解决了它:

response.request.res.responseUrl

Nicholas的答案未能获得端口(例如localhost:8080