“NetworkError:Ajax调用中的405方法不允许错误

时间:2015-09-18 12:10:54

标签: javascript jquery ajax

我创建了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).错误。这是我的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 ..

更新

当我尝试从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 个答案:

答案 0 :(得分:1)

现代浏览器对于从不同“域”检索内容有非常严格的规则。从本地文件系统(您的HTML /脚本)检索内容与向localhost(您的ajax调用)发出网络请求不同,因此Chrome会将其视为跨域请求。

为了使跨域请求成功,您还需要从http://localhost:64132/ URL提供HTML内容/脚本(因此它们位于同一个域中),或者您需要设置启动REST服务以实现CORS舞蹈,以允许您的file: URL访问它。

如果不了解REST服务的实现细节,就无法为这两个选项提供具体说明。您选择的将取决于您打算如何在现实生活中(无论是否相同的域)部署页面和服务以及易于实施。如果您的REST服务部署在某种容器中,它可以提供实现CORS和/或提供初始页面的选项。

相同问题的随机示例(尽管此处的确切解决方案不太适用于您的具体情况):Access-Control-Allow-Origin header when Origin 'null' when trying to post data to a LOCAL application