Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slim Framework - jQuery $.ajax request - Method DELETE is not allowed by Access-Control-Allow-Methods

I am trying to use a REST API written in Slim Framework.

Get & Post methods work without any problem. But DELETE requests doesn't work. I get "Method DELETE is not allowed by Access-Control-Allow-Methods"

I have already allowed OPTIONS aswell as DELETE in headers. See code below.

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');
 });

What could be the reason for this request failure?

like image 958
Riz Avatar asked Nov 22 '13 12:11

Riz


People also ask

How do you delete a request on AJAX?

The working of the ajax delete request So we can use the ajax() function with type option as “$. ajax( 'http://time.jsontest.com', { type : “DELETE});”, where the first parameter is the URL of the data that to delete. So, if the request successful means that the specified data will get deleted.

How do I fix a CORS issue in AJAX?

Solution. To resolve this error, update your code to make the AJAX call to the new URL provided by the redirect. For more information, see the MDN article CORS request external redirect not allowed.

How to Allow Cross domain AJAX request?

For a successful cross-domain communication, we need to use dataType “jsonp” in jquery ajax call. JSONP or “JSON with padding” is a complement to the base JSON data format which provides a method to request data from a server in a different domain, something prohibited by typical web browsers.


1 Answers

The current version of Nginx (1.0.x) doesn’t seem to support HTTP OPTIONS requests. It returns 405 "Method Not Allowed" whenever this request is sent. I added headers in nginx server's config file which fixed my problem.

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;
     }

    }

--

like image 81
Riz Avatar answered Sep 28 '22 04:09

Riz