我目前正在尝试使用 Backbone.js,但我在处理 CORS 请求时遇到了一些麻烦。
我已经使用 Silex 设置了一个基本的基于 PHP 的 API,并将 Backbone 模型/集合设置为指向它。查看 Chrome 网络选项卡,我可以看到飞行前 OPTIONS 请求正在运行:
要求
OPTIONS /todo/ HTTP/1.1
Host: api.backbone.dev
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://backbone.dev
User-Agent: ...
Access-Control-Request-Headers: accept, origin, x-http-method-override, content-type
Accept: */*
Referer: http://backbone.dev/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-GB,en;q=0.8,en-US;q=0.6,de;q=0.4
回复
HTTP/1.1 200 OK
Server: nginx/1.4.2
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
X-Powered-By: PHP/5.5.1-2+debphp.org~precise+2
Access-Control-Allow-Origin: http://backbone.dev
Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS
Access-Control-Allow-Headers: X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, X-HTTP-Method-Override, Origin
Cache-Control: no-cache
Content-Encoding: gzip
但在 POST 上,控制台返回:
XMLHttpRequest cannot load http://api.backbone.dev/todo/. Origin http://backbone.dev is not allowed by Access-Control-Allow-Origin.
我的 Nginx 服务器块包括以下访问控制标头:
add_header 'Access-Control-Allow-Origin' 'http://backbone.dev';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Content-Type,Accept,X-HTTP-Method-Override,Origin';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
在我在 PHP 响应中添加以下标头之前,OPTIONS 请求根本不起作用:
array(
'Access-Control-Allow-Origin' => 'http://backbone.dev',
'Access-Control-Allow-Methods' => 'GET,PUT,POST,DELETE,OPTIONS',
'Access-Control-Allow-Headers' => 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, X-HTTP-Method-Override, Origin'
);
现在 POST 请求没有返回任何内容。
我真的看不出这个请求出了什么问题。任何帮助表示赞赏。