2015-08-19 36 views
0

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; 
    } 
} 
+0

'這看起來像一個CORS問題。「 - 爲什麼? ''但是通常情況下,當readyState等於4時,狀態等於0.' - 你是否說過_alert(hit)_ **當readyState === 4和status === 0時會被調用? –

+0

@JaromandaX:status有時等於0,有時是200.後者是預期的,然後調用alert()。由於跨域問題,狀態0是瀏覽器拒絕將結果傳遞給JavaScript的典型結果。 – masa

回答

0

的實際問題,是不是在我的原始描述可見。什麼似乎是一個可行的解決方案是修改sendMessage()返回false

function sendMessage() { 
    ... 
    xhr.send(params); 

    return false; 
} 

這將是很想知道,爲什麼這是必要的。我通過研究頁面重定向(分配window.location.href)失敗的案例找到了解決方案,並且建議的解決方案是將return false添加到相關表單提交。這甚至不是表格提交...