代码之家  ›  专栏  ›  技术社区  ›  Lara

“NetworkError:Ajax调用中405 Method Not Allowed错误

  •  1
  • Lara  · 技术社区  · 11 年前

    我创建了一个 REST 服务,我测试了它 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.
    
    1 回复  |  直到 11 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

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

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

    如果不知道REST服务是如何实现的详细信息,就不可能给出任何一种选项的具体说明。您的选择将取决于您打算如何在现实生活中部署页面和服务(是否为同一域)以及实现的容易程度。如果您的REST服务部署在某种容器中,它可能会提供实现CORS和/或服务初始页面的选项。

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