PUT和DELETE请求在PHP REST API上失败,但POST和GET可以


PUT and DELETE requests unsuccessful on PHP REST API, but POST and GET are fine

我已经构建了一个slimPHP REST API。以下是我的标题:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true"); 
header('Access-Control-Allow-Headers: origin, content-type, accept');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');
header('Access-Control-Max-Age: 86400'); 

然而,当我尝试跨域PUT或DELETE请求时,我得到的只是(示例域):

XMLHttpRequest cannot load http://www.example.com/api/x.
Origin http://www.example.com is not allowed by Access-Control-Allow-Origin. 

如果Access Control Allow Origin设置为*,你知道为什么会发生这种情况吗?

来自Slim Framework文档:

不幸的是,现代浏览器不提供对HTTPPUT请求的本机支持。要绕过这个限制,请确保HTML表单的方法属性是"post",然后在HTML表单中添加一个方法覆盖参数,如下所示:

    <form action="/books/1" method="post">
        ... other form fields here...
        <input type="hidden" name="_METHOD" value="PUT"/>
        <input type="submit" value="Update Book"/>
    </form>

如果您使用的是Backbone.js或命令行HTTP客户端,也可以使用X-HTTP-method-override头来覆盖HTTP方法。

您可以使用任何想要的请求类型(包括像foo这样的自定义请求类型),但GET和POST是现代浏览器唯一本机支持的请求类型。