【问题标题】:405 method not allowed using $http service AngularJS405 方法不允许使用 $http 服务 AngularJS
【发布时间】:2017-12-03 06:53:56
【问题描述】:

我从 localhost 发出请求时收到 405 错误,这是完整的错误:

选项http://www.myurl.com 405(方法不允许)

XMLHttpRequest 无法加载 http://www.myurl.com。预检响应包含无效的 HTTP 状态代码 405

我理解这个问题,但奇怪的是我在使用 angular $http 服务时遇到了这个错误:

var req = {
    method: 'POST',
    url: 'http://www.myurl.com',
    headers: {
        'Content-Type': 'application/json'
    },
    data: {
    }
}

$http(req)
    .then(function(res) {},
        function(error) {});

使用 XMLHttpRequest 效果很好:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        console.log(xhttp.responseText);
    }
};
xhttp.open("POST", 'http://www.myurl.com', true);
xhttp.send();

我有一个 chrome 扩展来添加 CORS 标头,它正在工作。我还注意到,如果我删除 xhttp.open 中的第三个参数,则会再次出现错误。

¿有人知道原因吗? ¿如何使用角度服务而不出现错误?

【问题讨论】:

    标签: angularjs http xmlhttprequest http-status-code-405


    【解决方案1】:

    你可以这样写。因为您没有向 url 发送任何参数。所以我认为这是一个很好的方法。试试吧,它可能对你有用。

    $http.post('http://www.myurl.com').
    success(function(data) {
         //success Response here
    });
    

    【讨论】:

      【解决方案2】:

      您需要在服务器端允许 OPTIONS 方法。在每个 GET、POST、PUT、DELETE... 请求之前,都会启动一个 OPTIONS 请求。

      我建议您禁用“添加 CORS 的 chrome 扩展”,以使最终用户具有相同的配置。

      【讨论】:

        猜你喜欢
        • 2016-03-08
        • 2017-08-16
        • 1970-01-01
        • 1970-01-01
        • 2016-12-03
        • 2016-05-15
        • 1970-01-01
        • 2018-12-20
        • 2015-11-02
        相关资源
        最近更新 更多