問題描述
我試圖修改 adblockplus 代碼以進(jìn)行測試.我正在修改代碼以在 URL 上發(fā)送 http get 請(qǐng)求并從響應(yīng)中獲取最終 URL.我嘗試使用下面的代碼,但響應(yīng)不包含標(biāo)頭響應(yīng)中的 Location 字段.我在 Firefox 擴(kuò)展中這樣做,所以我認(rèn)為跨域請(qǐng)求不會(huì)有任何問題.為什么我無法從響應(yīng)中獲取 Location 字段?有沒有更好的方法來完成這項(xiàng)任務(wù)?
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 ?
輸入網(wǎng)址- http://netspiderads3.indiatimes.com/ads.dll/clickthrough?msid=17796167&cid=3224&slotid=1203&nsRndNo=817685688
預(yù)期輸出-http://www.mensxp.com/
實(shí)際輸出-位置:空
這是我正在使用的代碼-
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());
}
}
}
解決方案-
我終于找到了解決方案.我沒有得到最終的回應(yīng).所以我將重定向限制設(shè)置為 0,現(xiàn)在我可以在標(biāo)題中獲取 Location 字段.這是我添加到代碼中的內(nèi)容-
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;
推薦答案
其實(shí)你要檢查readyState == 2
,也就是HEADERS_RECEIVED狀態(tài)
Actually you have to check for readyState == 2
, that is HEADERS_RECEIVED state
這篇關(guān)于XMLHTTPRequest 響應(yīng)在標(biāo)頭中不包含 Location 字段的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!