【发布时间】:2013-10-24 21:40:43
【问题描述】:
我正在尝试创建一个 RESTful Web 服务,但在实现 PUT 请求时遇到了困难。我已尝试关注此网站上的其他答案以及 Mozilla 的各种文章,但未能成功。
请求是从域wwwtest.dev-box 生成的,它将发送到test.dev-box(基本上是一个前端应用程序调用后端应用程序)。以下是我从 Live HTTP 标头中捕获的标头:
http://test.dev-box/resource/v1/data/user/1
OPTIONS /resource/v1/data/user/1 HTTP/1.1
Host: test.dev-box
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://wwwtest.dev-box
Access-Control-Request-Method: PUT
Connection: keep-alive
HTTP/1.1 405 Method Not Allowed
Date: Wed, 16 Oct 2013 16:15:58 GMT
Server: Apache/2.2.15 (Red Hat)
x-powered-by: PHP/5.3.27
Access-Control-Allow-Origin: http://wwwtest.dev-box
Access-Control-Allow-Methods: POST, GET, PUT, OPTIONS
Access-Control-Max-Age: 1728000
Content-Length: 0
Allow: PUT
Cache-Control: no-cache
Connection: close
Content-Type: text/html; charset=UTF-8
我正在使用一个框架,所以所有内容都被路由到 web.php,它在页面顶部包含以下代码(取自this MDN article):
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header('Access-Control-Allow-Origin: http://wwwtest.dev-box');
header('Access-Control-Allow-Methods: POST, GET, PUT, OPTIONS');
header('Access-Control-Max-Age: 1728000');
header("Content-Length: 0");
header("Content-Type: text/plain");
} else {
header("HTTP/1.1 403 Access Forbidden");
header("Content-Type: text/plain");
}
在我的代码发出 PUT 请求之前,它首先发送 CORS 预检 OPTIONS 请求(从上面的捕获中可以看到)。必要的标头应附加到响应中,并告诉请求者允许 PUT。不幸的是,正如您从上面的响应标头中看到的那样,即使 PUT 在响应 access-control-allow-methods 中,它仍然返回 405 Method Not Allowed。
这是我正在使用的框架 (Silex) 的 .htaccess 文件:
<IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ web.php [QSA,L]
</IfModule>
【问题讨论】:
标签: php http-headers cors silex