2

我使用 PHP 中的 Fat Free Framework 编写了一个 REST-ful API,并且正在使用backbone.js 进行调用。当我尝试保存新的 Orders 模型时,我的应用程序发出 PUT 请求,服务器返回 406 错误。

Request Method:PUT
Status Code:406 Not Acceptable

Request Headers
Accept:application/json, text/javascript, */*; q=0.01
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:174
Content-Type:application/json
Cookie:__utma=239804689.76636928.1286699220.1305666110.1325104376.94; __utmz=239804689.1325104376.94.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); PHPSESSID=935d2632fd0d12a1a0df4cb0f392eb5e
X-Requested-With:XMLHttpRequest

Request Payload
{"id":0,"customerId":0,"lastPage":"items","priceConfig":null,"items":null,"saveStatus":0,"savedAt":1326588395899,"name":null}

Response Headers
Connection:Keep-Alive
Content-Length:460
Content-Type:text/html; charset=iso-8859-1
Date:Sun, 15 Jan 2012 00:46:37 GMT
Keep-Alive:timeout=5, max=98
Server:Apache

我的 .htaccess 文件如下所示:

# Enable rewrite engine and route requests to framework
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L,QSA]

# Disable ETags
<IfModule mod_headers.c>
    Header Unset ETag
    FileETag none
</IfModule>

# Default expires header if none specified (stay in browser cache for 7 days)
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresDefault A604800
</IfModule>

<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>

我的网站应用程序在我的本地服务器上运行良好,并且只在我的网络服务器上运行。任何想法出了什么问题?

4

1 回答 1

1

我想出了一个解决方法。

我相信我的服务器正在使用 mod_security2 来阻止 PUT 和 DELETE 请求。我正在等待他们的回复,并且无法在 .htaccess 文件中禁用 mod_security2,所以我无能为力。

在 .htaccess 文件中使用“脚本 PUT /文件名”会导致 500 错误:“此处不允许脚本”,我不知道为什么,但我决定不处理重新配置我的网络主机以处理 PUT 和 DELETE。

为了保持我的 API REST-ful,我保留了 PUT 和 DELETE 的正常处理,并将其添加到 POST 处理中:

function post() {
    //if Backbone.emulateHTTP is true, emulate PUT
    $data = json_decode(F3::get('REQBODY'), true);
    $type = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']; //PUT, DELETE, POST
    if ($type == 'PUT') {
        $this->put();
        return;
    }
    if ($type == 'DELETE') {
        $this->delete();
        return;
    }

    //handle normal POST here
}

如果你设置 Backbone.emulateHTTP = true; 它将请求方法保留为 POST,并将 X-HTTP-Method-Override 作为 PUT 或 DELETE 发送。

我喜欢这个,因为我可以保持我的 REST-ful 实现完整,并且当我发布到我的网络服务器时,只需注释掉 emulateHTTP 代码。

于 2012-01-15T20:33:37.413 回答