Slim框架 - jQuery $.ajax请求 - Access-Control-Allow-Methods不允许使用DELETE方法。

6

我正在尝试使用Slim Framework编写的REST API。

GET和POST方法可以正常工作,但DELETE请求无法正常工作。 我收到“Method DELETE is not allowed by Access-Control-Allow-Methods”的错误提示。

我已经在标头中允许了OPTIONS和DELETE。请参见下面的代码。

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');

$app->options('/(:name+)', function() use($app) {                  
    $response = $app->response();
    $app->response()->status(200);
    $response->header('Access-Control-Allow-Origin', '*'); 
    $response->header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, X-authentication, X-client');
    $response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
 });

这个请求失败的原因是什么?
1个回答

6

Nginx当前版本(1.0.x)似乎不支持HTTP OPTIONS请求。每当发送此请求时,它会返回405 "Method Not Allowed"。我在nginx服务器的配置文件中添加了头部信息来解决我的问题。

location / {
        alias   /usr/share/nginx/webapp/;
        try_files $uri $uri/ /index.php;
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
            add_header 'Access-Control-Allow-Methods' "GET, POST, OPTIONS, DELETE";
            add_header 'Access-Control-Max-Age' 1728000;
        return 200;
     }

    }

--


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接