我有一个奇怪的问题。我正在使用 Angular.js 1.2.15 对此进行测试。
我想向另一个域上的 RESTful API 后端发送一个 POST 请求(我想直接使用 $http,而不是 $resource)。
var mapData = {
'some': 'keys',
'other': 'keys'
}
$http.post(endPoint, mapData);
这就是发生的情况:首先发送一个 OPTIONS 请求,并带有以下请求标头:
OPTIONS /api/maps HTTP/1.1
Host: myhost.com
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://0.0.0.0:9000
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/36.0.1985.125 Chrome/36.0.1985.125 Safari/537.36
Access-Control-Request-Headers: accept, content-type
Accept: */*
Referer: http://0.0.0.0:9000/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
响应清楚地表明,允许来自其他来源和使用每种方法的请求:
HTTP/1.1 204 No content
Server: Varnish
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: *
Access-Control-Allow-Headers: DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type
Access-Control-Max-Age: 0
Content-Type: text/plain charset=UTF-8
Accept-Ranges: bytes
Date: Tue, 02 Sep 2014 14:50:16 GMT
X-Varnish: 166874803
Age: 0
Via: 1.1 varnish
Connection: close
Cache-Control: max-age=0, private
X-Varnish-Cache: MISS
但是,POST 请求甚至不会由浏览器(Chromium 36)发送,即它不会在开发控制台的网络选项卡中显示 POST 请求。相反,控制台中显示以下内容:
XMLHttpRequest cannot load http://myhost.com/api/maps. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://0.0.0.0:9000' is therefore not allowed access.
现在,完全奇怪的是:对同一个 API 的 GET 请求工作,并且前面没有 OPTIONS 请求(或者它可能没有显示在网络选项卡中)。
HTTP/1.1 304 Not Modified
Server: nginx/1.4.7
Content-Type: application/json; charset=utf-8
Status: 200 OK
X-UA-Compatible: IE=Edge,chrome=1
ETag: "baca3b7547fed3377088eb81fe083ff8"
X-Request-Id: b2552dc4fdef2541c841e3d5e12d337e
X-Runtime: 0.110003
X-Rack-Cache: miss
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS
Access-Control-Allow-Headers: DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type
Accept-Ranges: bytes
Date: Tue, 02 Sep 2014 14:54:31 GMT
X-Varnish: 166874831 166874142
Age: 6223
Via: 1.1 varnish
Connection: keep-alive
Cache-Control: max-age=0, private
X-Varnish-Cache: HIT
我真的不知道这里有什么问题。是 Angular 的实现吗?还是服务器配置错误?负责 API 的人告诉我,它通常适用于他们所有的网络应用程序。
我知道这是一个 CORS 问题,在这方面我绝不是专家,但是,嘿,Access-Control-Allow-Origin: *
应该做的伎俩,不是吗?
更新:它在使用 plain 时有效XMLHttpRequest
:
var http = new XMLHttpRequest();
var url = endPoint;
var params = JSON.stringify(mapData);
http.open("POST", url, true);
我退了200。这是怎么回事?