【发布时间】:2015-09-18 12:10:53
【问题描述】:
我创建了一个 RESTservice 并在 Chrome REST Console 上对其进行了测试。它工作正常,我得到了响应,但是在 jquery Ajax 使用相同的内容时,我得到了 "NetworkError: 405 Method Not Allowed error in Ajax Call 和 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:64132/Auth. (Reason: CORS request failed). 错误。这是我的 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");
}
});
请帮助我更正此问题并成功调用服务。谢谢..
更新
当我尝试从 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.
【问题讨论】:
-
你在服务器端使用什么
-
type: 'POST',试试type: 'GET', -
这是一个 CORS 问题,您需要在 Rest 服务中设置
Access-Control-Allow-Origin: http://localhost:64132/。 -
@Lara 那么你不是从 localhost 运行,而是在 file:// 上运行并访问 localhost,因此是 CORS。请参阅下面的答案。
标签: javascript jquery ajax