PUT的跨域jQuery $ .ajax请求失败(Access-Control-Allow-Methods不允许使用方法PUT。)

时间:2022-08-22 19:17:10

I am doing cross domain requests via jQuery's $.ajax to access a RESTful PHP API.
In order to do so I have set the following headers in PHP:

我正在通过jQuery的$ .ajax进行跨域请求来访问RESTful PHP API。为此,我在PHP中设置了以下标头:

header("HTTP/1.1 $code $status");
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT');

Using the types GET and POST works without problems. However when I do a PUT ajax call Firefox fails completely and shows OPTIONS api.php in the network tab of Firebug.
In Chrome the same thing happens first (OPTION request fails with message Method PUT is not allowed by Access-Control-Allow-Methods.) but Chrome follows up with the actual PUT request that actually works then.

使用类型GET和POST可以正常工作。但是,当我执行PUT时,ajax调用Firefox完全失败,并在Firebug的网络选项卡中显示OPTIONS api.php。在Chrome中,首先发生同样的事情(OPTION请求失败,并且Access-Control-Allow-Methods不允许使用方法PUT消息。)但Chrome会跟进实际工作的实际PUT请求。

What is the reason for this behaviour?

这种行为的原因是什么?

1 个解决方案

#1


17  

Apparently the browser first sends an OPTIONS request to find out if PUT (or DELETE) requests are allowed.
Since I had not allowed the OPTIONS method in Access-Control-Allow-Methods it failed and so did the PUT request after in Firefox.
Adding OPTIONS to Access-Control-Allow-Methods solved the problem:

显然,浏览器首先发送OPTIONS请求以查明是否允许PUT(或DELETE)请求。由于我没有在Access-Control-Allow-Methods中允许OPTIONS方法,因此在Firefox之后PUT请求失败了。将选项添加到Access-Control-Allow-Methods解决了以下问题:

header('Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS');

#1


17  

Apparently the browser first sends an OPTIONS request to find out if PUT (or DELETE) requests are allowed.
Since I had not allowed the OPTIONS method in Access-Control-Allow-Methods it failed and so did the PUT request after in Firefox.
Adding OPTIONS to Access-Control-Allow-Methods solved the problem:

显然,浏览器首先发送OPTIONS请求以查明是否允许PUT(或DELETE)请求。由于我没有在Access-Control-Allow-Methods中允许OPTIONS方法,因此在Firefox之后PUT请求失败了。将选项添加到Access-Control-Allow-Methods解决了以下问题:

header('Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS');