XMLHTTPRequest 响应在标头中不包含 Location 字段

XMLHTTPRequest response doesnt contain Location field in the header(XMLHTTPRequest 响应在标头中不包含 Location 字段)

本文介绍了XMLHTTPRequest 响应在标头中不包含 Location 字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图修改 adblockplus 代码以进行测试.我正在修改代码以在 URL 上发送 http get 请求并从响应中获取最终 URL.我尝试使用下面的代码,但响应不包含标头响应中的 Location 字段.我在 Firefox 扩展中这样做,所以我认为跨域请求不会有任何问题.为什么我无法从响应中获取 Location 字段?有没有更好的方法来完成这项任务?

I was trying to modify the adblockplus code for testing purpose. I was modifying the code to send a http get request on a URL and get the final URL from the response. I tried using the below code, but the response doesn't contain the Location field in the header response. I am doing this within a firefox-extension, so I dont think cross-domain request would be any issue. Why is it that I am not able to fetch the Location field from the response? Is there a better way to accomplish this task ?

输入网址- http://netspiderads3.indiatimes.com/ads.dll/clickthrough?msid=17796167&cid=3224&slotid=1203&nsRndNo=817685688

预期输出-http://www.mensxp.com/

实际输出-位置:空

这是我正在使用的代码-

Here is the code I am using-

function geturl(url){
let req= Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
req.open("GET", url);
req.overrideMimeType("text/plain");
req.send(null);
req.onreadystatechange = function() {
if (req.readyState == 4) 
{ if (req.status == 200) 
  { try 
    {
       location = req.getResponseHeader("Location");
       console.log("Location is: " + location);
    }
    catch(e){
    console.log("Error reading the response: " + e.toString());
  }
 }
}

解决方案-

我终于找到了解决方案.我没有得到最终的回应.所以我将重定向限制设置为 0,现在我可以在标题中获取 Location 字段.这是我添加到代码中的内容-

I finally found the solution for this. I was not getting the final response. So I set the redirection limit to 0, now I can get the Location field in the header. Here is what I added to my code-

if (request.channel instanceof Ci.nsIHttpChannel)
    request.channel.redirectionLimit = 0;

推荐答案

其实你要检查readyState == 2,也就是HEADERS_RECEIVED状态

Actually you have to check for readyState == 2, that is HEADERS_RECEIVED state

这篇关于XMLHTTPRequest 响应在标头中不包含 Location 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:XMLHTTPRequest 响应在标头中不包含 Location 字段

基础教程推荐