2015-09-18 91 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