简体   繁体   中英

Slim Framework v3 - Problems with PUT routes

Since I have upgraded to Slim v3 all my GET and POST routes are working well, but the PUT routes are not. I have a class where I do something like this:

$this->slimObj->put('/path/{ID}', array($this, 'method'));
function method ( $request, $response, $args ) { 
    $response = $response->withHeader('Content-type', 'application/json');
    $response = $response->withHeader('Access-Control-Allow-Origin', '*');
    $ID = $args['ID'];
    // ...
    return $response; 
}

I use Chrome 48 to debug my Cordova app and I get this error after that PUT call:

XMLHttpRequest cannot load 
http://example.com/file.php/path/149. No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:4400' is therefore not allowed access. The response had HTTP status code 400.

I use similar callbacks for GET and POST requests and they work fine, I don't understand why it does not work for PUT .

When calling that from curl it works:

curl -X PUT -H 'Content-Type: application/json' -d '{"data": 5 }' http://example.com/file.php/path/149

I call Slim API functions from JS using ajax :

$.ajax({
    type: 'PUT',
    url: 'http://example.com/file.php/path/149',
    dataType: "json", 
    data:  {
       "data": 5
    },
    success: function(result) {
        // ...
    },
    error: function() {
        // Always getting error
    }
});

How can I make it work from Chrome 48 ?

I'm not so sure but I think that everything was working fine with previous Chrome versions.

Thanks

I have just solved by adding this:

$this->slimObj->add(function ($request, $response, $next) {
    $response = $response->withHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
    $response = $next ($request, $response);
    return $response;
});

before initializing any route.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM