当我向http://www.example.com
提出请求时,为什么我会在webRequest.onBeforeRequestListener中看到http://www.example.com/
?
例如:
chrome.webRequest.onBeforeRequest.addListener(
details => console.log('Sending request to', details.url),
{ urls: ['<all_urls>'] });
fetch('http://www.example.com');
将打印
Sending request to http://www.example.com/
这与网络请求监视器中显示的请求URL一致。例如,如果我接受并将其转换为curl命令,则请求如下所示:
curl 'http://www.example.com/' -H 'Accept: */*' -H 'Connection: keep-alive'
-H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: en-US,en;q=0.9'
-H 'User-Agent: ...' --compressed
因此,原始请求仅针对http://www.example.com/
而不是http://www.example.com
。该决定必须在浏览器中进行,而不是由服务器进行。
使用XMLHttpRequest
代替fetch
时也会出现相同的行为。在我的示例中,我使用的是Chrome,但在Firefox上它是相同的。
问题:
onBeforeRequest
侦听器中过滤当前对特定URL的请求,您如何可靠地匹配它?例如,只检查URL是否相同将失败。答案 0 :(得分:1)
想想,我找到了。浏览器只是修复了无效的网址。
要引用Wikipedia,网址如下所示:
scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]
如果存在权限部分,则路径必须以单斜杠(/)开头,如果不是,则也可以以双斜杠开头。始终定义路径,但定义的路径可能为空(零长度),因此没有尾随斜杠。
http://example.com
具有权限部分(在此示例中,模式加主机名:http://example.com
),但这会使路径为空。根据规范,路径必须以/
开头,因此浏览器通过将/
替换为空路径来修复它。
如果您使用有效的网址,例如http://example.com/abc
,则无需修改。