如何在Postman预请求脚本中获取重定向后的响应URL?
在Postman预请求脚本中获取重定向后的最终URL
可行,但你之前的代码无效是因为Postman的response对象本身没有url属性,要获取最终重定向后的URL,得从response.request.url里取。
直接用这段代码就能拿到最终地址:
pm.sendRequest("https://foobar.com", function (err, response) { // 获取经过所有重定向后的最终URL const finalRedirectUrl = response.request.url.toString(); console.log(finalRedirectUrl); });
如果需要查看完整的重定向流程,可以遍历response.history数组,里面记录了每一次跳转的中间响应:
pm.sendRequest("https://foobar.com", function (err, response) { console.log("最终URL:", response.request.url.toString()); if (response.history.length > 0) { console.log("重定向步骤:"); response.history.forEach((step, idx) => { console.log(`${idx+1}. ${step.request.url.toString()} → ${step.headers.get('location')}`); }); } });
原理是:当请求发生重定向时,Postman会自动跟进所有跳转,最终的response.request对应最后一次请求的配置,它的url就是跳转后的最终地址;response.history则保存了每一次重定向的中间响应,能帮你梳理整个跳转链路。
内容的提问来源于stack exchange,提问作者Liam Bell
相关产品推荐
相关产品推荐

