我正在尝试从 AngularJS 发出 http get 请求。它仅适用于 Internet Explorer 11。当我尝试在 Chrome、Firefox 或 Edge 中进行 POST 调用时,它无法正常工作。
我收到以下错误:
这是我的 AngularJS 调用:
$http({
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
url: URL
}).then(function successCallback(response) {
console.log(response.data);
}, function errorCallback(response) {
console.log(response.status);
console.log(response.headers);
console.log(response.config);
});
作为后端,我有一个 Java Spring MVC 应用程序,并且设置了以下标头:
HttpHeaders responseHeader = new HttpHeaders();
responseHeader.set("Access-Control-Allow-Origin","*");
responseHeader.set("Access-Control-Allow-Headers:","Content-Type");
responseHeader.set("Access-Control-Allow-Methods","POST, GET, PUT, OPTIONS, DELETE");
responseHeader.set("Content-Type","application/json");
但是当我设置断点时,我看到 angular 永远不会到达后端!这很令人困惑,我已经在互联网上搜索了很多并尝试更改默认的 AngularJS Content-Type 标头:
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
我还尝试将 POST-Request 中的 Content-Type 更改为“application/x-www-form-urlencoded” - 没有效果。
注意:后端和前端运行在同一台开发机器上。唯一的区别是端口,这就是为什么我对我收到 CORS 错误感到困惑的原因......
我只有 POST-Requests 有这个问题;GET 就像一个魅力
编辑1:
我认为这是 cors 的问题并且我使用了不同的端口,但是我可以将其关闭吗?
编辑2:
现在我尝试让它与本地 tomcat 一起工作。现在我在 Tomcat 中看到请求将到达服务器:
<< Client IP>> - - [28/Jun/2017:13:43:24 +0200] "OPTIONS <<URL>> HTTP/1.1" 403 -
响应现在是 HTTP 403。在浏览器网络选项卡中,我可以看到以下请求标头:
Host: <<backend ip>>:8080
User-Agent: <<user agent>>
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: access-control-allow-origin,content-type
Origin: http://<<Ip of host>>
Connection: keep-alive
该请求标头的响应如下:
Content-Type: text/plain
Content-Length: 0
Date: Wed, 28 Jun 2017 11:43:24 GMT
我已经像tomcat文档中的例子一样设置了cors过滤器:http : //tomcat.apache.org/tomcat-7.0-doc/config/filter.html#CORS_Filter
当我发出 get 请求时,它仍在工作并且所有 CORS 标头都存在。我认为第一个 OPTIONS 请求有问题。不知道为什么tomcat在OPTIONS请求来的时候不设置CORS头。
我想到了。我制作了一个全新的 angularjs 测试网站。这是我的工作 angularjs 代码:
var req = {
method: 'POST',
url: 'myURL',
headers: {
'Content-Type': undefined
},
data: "JSON BODY DATA"
}
$http(req).then(function successCallback(response) {
console.log(response.data);
}, function errorCallback(response) {
console.log(response.data);
});
}]);
我删除了更改默认 angularjs 标头的任何内容。我的 Spring MVC 应用程序的标题如下:
HttpHeaders responseHeader = new HttpHeaders();
responseHeader.set("Access-Control-Allow-Origin","http://<<clientip>>");
responseHeader.set("Access-Control-Allow-Headers:","Content-Type");
responseHeader.set("Access-Control-Allow-Methods","POST, GET, PUT, OPTIONS, DELETE");
responseHeader.set("Content-Type","application/json");
我不知道它现在工作的确切原因。也许是因为我修改了 AngularJS 中的默认标题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句