從http://localhost:8080 JavaScript的請求行爲不一致:CORS問題與POST,在Chrome
function sendMessage() {
var params =
'AppKey=' + config.appKey +
'&MetadataJson=' + encodeURIComponent(config.metadataJson),
url = 'http://localhost/Controller/Action',
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
alert('hit!');
}
}
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.withCredentials = true;
xhr.send(params);
}
翻譯成HTTP請求:
POST http://localhost//Controller/Action HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 667
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: */*
Referer: http://localhost:8080/index.html
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
Cookie: ASP.NET_SessionId=aoqjuh2xob20qt5jpe2jo01i
AppKey=...
HTTP響應:
HTTP/1.1 200 OK
Cache-Control: private
Server: Microsoft-IIS/8.5
Access-Control-Allow-Origin: http://localhost:8080
Access-Control-Allow-Credentials: true
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Wed, 19 Aug 2015 06:17:02 GMT
Content-Length: 0
但是:瀏覽器中的行爲(Chrome)並不一致。有時alert('hit!')
被按預期調用,但通常在readyState
等於4時,status
等於0。
這看起來像是一個CORS問題。對我來說,似乎與CORS相關的請求中唯一的標題字段是Origin
,服務器響應的Access-Control-Allow-Origin
具有相同的值,因此從CORS的角度來看,所有內容都應該可以正常使用?
有關如何更改JavaScript或服務器實現(ASP.NET MVC)的任何建議?
UPDATE:
的相關HTML:
<li class="my-link">
<a href="">Get Help</a>
</li>
...和JavaScript到HTML連接到sendMessage()
:
window.onload = function() {
var els = document.getElementsByClassName('my-link'), i;
for (i = 0; i < els.length; i += 1) {
els[i].onclick = sendMessage;
}
}
'這看起來像一個CORS問題。「 - 爲什麼? ''但是通常情況下,當readyState等於4時,狀態等於0.' - 你是否說過_alert(hit)_ **當readyState === 4和status === 0時會被調用? –
@JaromandaX:status有時等於0,有時是200.後者是預期的,然後調用alert()。由於跨域問題,狀態0是瀏覽器拒絕將結果傳遞給JavaScript的典型結果。 – masa