【发布时间】:2013-03-07 13:58:33
【问题描述】:
我正在尝试使用来自 Angular(版本 1.0.5)webapp 的应用程序密钥和令牌来练习 Trello API。服务器似乎正确配置为处理CORS。来自enable cors 的带有http://test-cors.org 的测试请求按预期工作。
当我在我的一个角度控制器中发出发布请求时:
$http.post(url).success(function(data) {
$scope.server_resp = data;
});
我收到 请求标头字段 Content-Type is not allowed by Access-Control-Allow-Headers 错误。 (尽管如下所示,Access-Control-Allow-Origin 设置为“*”)。为什么要加这个header,能去掉吗?
XMLHttpRequest
当我使用原始 XMLHttpRequest 发出相同的请求时,它会成功。以下是 XMLHttpRequest 的标头:
Request Method:POST
Status Code:200 OK
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:0
Host:api.trello.com
Origin:http://192.168.0.125:9000
Referer:http://192.168.0.125:9000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22
Response
Access-Control-Allow-Methods:GET, PUT, POST, DELETE
Access-Control-Allow-Origin:*
Cache-Control:max-age=0, must-revalidate, no-cache, no-store
Content-Length:563
Content-Type:application/json
Date:Mon, 18 Mar 2013 02:49:37 GMT
Expires:Thu, 01 Jan 1970 00:00:00
X-Powered-By:Express
X-Server-Time:1363574977568
Angular $http.post
以下是 Angular 发起请求的标头。请注意,浏览器发出了飞行前 OPTIONS 请求:
Request Method:OPTIONS
Status Code:200 OK
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, origin, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:api.trello.com
Origin:http://192.168.0.125:9000
Referer:http://192.168.0.125:9000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22
Response
Access-Control-Allow-Methods:GET, PUT, POST, DELETE
Access-Control-Allow-Origin:*
Content-Length:0
Content-Type:text/html; charset=utf-8
Date:Mon, 18 Mar 2013 02:51:00 GMT
X-Powered-By:Express
有没有办法配置 Angular 的请求标头以允许上面的 $http.post() 代码工作?
【问题讨论】:
-
这是因为响应来自另一个域,并且它们在服务来自其他域的请求时有自己的规则。
-
你可以尝试
$http.jsonp()从另一个域获得响应 -
@Abilash 因为我想做一个帖子,jsonp 不是一个选项(我记得它只用于获取请求)。
-
我对 CORS 的了解并不如我所愿,但我注意到您的(预检?)Angular 响应定义了允许的内容类型:“text/html; charset=utf-8”。您的 XHR 响应返回 Content-Type:“application/json”。在我看来,问题不是 CORS,而是数据类型不匹配。
-
大卫,你找到解决方案了吗?我仍在寻找这个问题的答案:(
标签: angularjs