XMLHTTPRequest response doesnt contain Location field in the header

回眸只為那壹抹淺笑 提交于 2021-02-04 19:34:26

问题


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 ?

Input URL- http://netspiderads3.indiatimes.com/ads.dll/clickthrough?msid=17796167&cid=3224&slotid=1203&nsRndNo=817685688

Expected output-http://www.mensxp.com/

Actual Output- Location: null

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());
  }
 }
}

Solution-

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;

回答1:


Because the status code 200 mean OK, so your try block won't be executed. "Location" field only exits in redirect, which status code is 301 or 302.

That url response 302, so change req.status == 200 to req.status == 302.




回答2:


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



来源:https://stackoverflow.com/questions/15964254/xmlhttprequest-response-doesnt-contain-location-field-in-the-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!