2017-08-10 175 views
0

使用AJAX從瀏覽器到外部地址很容易(即在瀏覽器外部,即使它是localhost),但我有一個不同的問題。瀏覽器是否可以向自己發送HTTP請求?

是否有某種對象或服務允許瀏覽器向自己發送(或模擬)HTTP請求,例如:來自JavaScript?

E.g.從Firefox我可以看到下面的原始請求:

GET /headers.php HTTP/1.1 
Host: localhost 
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:49.0) Gecko/20100101 Firefox/49.0 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
Accept-Language: en-GB,en;q=0.5 
Accept-Encoding: gzip, deflate 
Connection: keep-alive 
Upgrade-Insecure-Requests: 1 
Cache-Control: max-age=0 

,並通過使用PHP腳本(GET要求上述headers.php):

<pre> 
<?php 
print_r(apache_request_headers()); 

我可以在網頁上看到以下內容:

[Content-Type] => 
[Content-Length] => 0 
[Upgrade-Insecure-Requests] => 1 
[User-Agent] => Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:49.0) Gecko/20100101 Firefox/49.0 
[Host] => localhost 
[Accept-Language] => en-GB,en;q=0.5 
[Accept-Encoding] => gzip, deflate 
[Accept] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
[Connection] => keep-alive 
[Cache-Control] => max-age=0 

我可以通過JavaScript獲得相同的信息,而無需調用服務器腳本嗎?

+2

你是什麼意思*「自己」*你有什麼用例?就像我不能真正看到瀏覽器的服務,你可以請求... UserAgent樣式表可能嗎? – Kaiido

+0

@Kaiido用例:做一個假的請求,得到'Accept-Languages'請求頭,否則在沒有服務器的情況下不能使用這個請求頭將值回顯給瀏覽器。 –

+0

@CJDennis您是否正在嘗試創建一個'HEAD'或'OPTIONS'請求[爲什麼Fetch API將第一個PUT請求作爲選項發送](https://stackoverflow.com/q/42311018/),https:// stackoverflow .COM /問題/ 42311018 /爲什麼 - 不取-API發送-的先放,請求作爲選項/ 42311206#comment71821815_42311018? – guest271314

回答

相關問題