2015-09-18 148 views
1

我創建了一個REST服務,我測試它在Chrome REST Console。它的工作正常,我得到的響應,但同時通過jquery Ajax我得到"NetworkError: 405 Method Not Allowed error in Ajax CallCross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:64132/Auth. (Reason: CORS request failed). error.Here是我的Ajax代碼..「NetworkError:405方法不允許在Ajax調用中的錯誤

var UserDetails = { "UserName": "Bond", "Password": "password" }; 

$.ajax({ 
    type: 'POST', 
    url: 'http://localhost:64132/Auth', 
    crossDomain: true, 
    data: UserDetails, 
    contentType: "application/json; charset=utf-8", 
    success: function (data) { 

     alert(data.UserName); 
    }, 
    error: function (XMLHttpRequest, textStatus, errorThrown) { 
     alert("some error"); 
    } 
}); 

請幫我糾正這一點,併成功地調用Service.Thanks ..

更新

當我試圖ŧ O調用從Chrome中的服務我收到以下錯誤控制檯..

Failed to load resource: the server responded with a status of 405 (Method Not Allowed) 
Test.html:1 XMLHttpRequest cannot load http://localhost:64132/Auth. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 405. 
+1

https://developer.mozilla.org/en-US/docs/Web/HTTP/ Access_control_CORS – Eric

+1

您在服務器端使用的是什麼 –

+0

'type:'POST','嘗試'type:'GET',' – Jai

回答

1

現代的瀏覽器有關檢索來自不同的「域」的內容非常嚴格的規定。從您的本地文件系統(您的HTML /腳本)檢索內容與發出localhost(您的ajax調用)的網絡請求不同,因此Chrome會將其視爲跨域請求。

爲了使跨域請求成功,您也需要從http://localhost:64132/網址提供HTML內容/腳本(因此它們位於同一個域中),或者您需要設置您的REST服務來實施CORS舞蹈,以允許您的file:網址訪問它。

不知道您的REST服務如何實現的細節,因此無法爲任何選項提供具體說明。您選擇哪個將取決於您打算如何在現實生活中(相同域或不相同)部署頁面和服務,以及實施的便利性。如果您的REST服務部署在某種容器中,它可以提供用於實現CORS的選項和/或用於提供初始頁面的選項。

同一問題的隨機實例(儘管這裏的精確解是不太可能爲您的特定情況下工作):Access-Control-Allow-Origin header when Origin 'null' when trying to post data to a LOCAL application