我有一臺機器在我的本地局域網(machineA)上有兩臺Web服務器。第一個是XBMC內置的(在端口8080上)並顯示我們的庫。第二個服務器是一個CherryPy python腳本(端口8081),我用它來根據需要觸發文件轉換。文件轉換由來自XBMC服務器提供頁面的AJAX POST請求觸發。如何獲得跨源資源共享(CORS)後請求工作
- 轉到http://machineA:8080它顯示庫
- 庫顯示
- 用戶點擊 '轉換' 鏈接,發出以下命令 -
jQuery的Ajax請求
$.post('http://machineA:8081', {file_url: 'asfd'}, function(d){console.log(d)})
- 瀏覽器發出HT帶有以下標題的TP OPTIONS請求;
請求報頭 - OPTIONS
Host: machineA:8081
User-Agent: ... Firefox/4.01
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Origin: http://machineA:8080
Access-Control-Request-Method: POST
Access-Control-Request-Headers: x-requested-with
- 服務器出現以下響應;
響應頭 - OPTIONS(STATUS = 200行)
Content-Length: 0
Access-Control-Allow-Headers: *
Access-Control-Max-Age: 1728000
Server: CherryPy/3.2.0
Date: Thu, 21 Apr 2011 22:40:29 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Content-Type: text/html;charset=ISO-8859-1
- 談話然後停止。 (?)的瀏覽器,在理論上,發出POST請求的服務器用正確的迴應CORS標頭(訪問控制允許來源:*)
爲了排除故障,我也發表了同樣的$ .post命令從http://jquery.com。這是我被困在jquery.com,post請求工作的地方,OPTIONS請求在POST之後發送。此交易的標題如下所示;
請求報頭 - OPTIONS
Host: machineA:8081
User-Agent: ... Firefox/4.01
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Origin: http://jquery.com
Access-Control-Request-Method: POST
響應頭 - OPTIONS(STATUS = 200行)
Content-Length: 0
Access-Control-Allow-Headers: *
Access-Control-Max-Age: 1728000
Server: CherryPy/3.2.0
Date: Thu, 21 Apr 2011 22:37:59 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Content-Type: text/html;charset=ISO-8859-1
請求報頭 - POST
Host: machineA:8081
User-Agent: ... Firefox/4.01
Accept: */*
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://jquery.com/
Content-Length: 12
Origin: http://jquery.com
Pragma: no-cache
Cache-Control: no-cache
響應頭 - POST(STATUS = 200 OK)
Content-Length: 32
Access-Control-Allow-Headers: *
Access-Control-Max-Age: 1728000
Server: CherryPy/3.2.0
Date: Thu, 21 Apr 2011 22:37:59 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Content-Type: application/json
我想不通,爲什麼同樣的要求會從一個站點工作,而不是其他。我希望有人能夠指出我缺少的東西。謝謝你的幫助!
是CORS需要如果兩個Web服務器在同一臺機器上? – jdigital 2011-04-21 23:48:09
據我所知,這是一個CORS請求,因爲不同的端口。另外,OPTIONS請求表明瀏覽器正在將它視爲CORS請求 – James 2011-04-22 03:02:50
[CORS POST請求可能來自普通javascript,但爲什麼不使用jQuery?](https://stackoverflow.com/questions/5584923/) a-cors-post-request-works-from-plain-javascript-but-why-not-with-jquery) – Liam 2018-02-27 16:30:27