Search code examples
phphttpslimput

Slim v4 - Can't get body from PUT requests


I'm trying to do a PUT request with a Slim route.

I'have no problem doing it with a POST request, but when i try to do it with PUT, the variable $body (in the example below) results "NULL". Also by the variable $args['id'] i can get the parameter "id" from the url.

    $app->put('/networks/{id}', function ($request,$response,$args) {
        $body = $request->getParsedBody();
        var_dump($body,1); 
        die();
        [...]
    });

The request headers

PUT /mysite/networks/1 HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:98.0) Gecko/20100101 Firefox/98.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2NDc2MTkzMDgsImV4cCI6MTY0NzYyMTEwOCwianRpIjoiNTg5MzNiZmY3ZDQwZmY2NmU4YmJhMjA0YzM1MDVkMTMiLCJpZCI6IjIwIiwiZW1haWwiOiJhZG1pbkBnbWFpbC5jb20iLCJtYXRyaWNvbGEiOiJNTVNEQSJ9.WBLAwfxlcT2vXTQugxYbYgSSb_XNaBREWXxTXSGSsdQ
X-Requested-With: XMLHttpRequest
Content-Length: 81
Origin: http://localhost
Connection: keep-alive
Referer: http://localhost/anas-ta/public/index.html
Cookie: _pk_id.1.1fff=0fb970783be6ee60.1646993471.; jwt_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2NDc2MTkzMDgsImV4cCI6MTY0NzYyMTEwOCwianRpIjoiNTg5MzNiZmY3ZDQwZmY2NmU4YmJhMjA0YzM1MDVkMTMiLCJpZCI6IjIwIiwiZW1haWwiOiJhZG1pbkBnbWFpbC5jb20iLCJtYXRyaWNvbGEiOiJNTVNEQSJ9.WBLAwfxlcT2vXTQugxYbYgSSb_XNaBREWXxTXSGSsdQ
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin

This is an example request body sended with header "x-www-form-urlencoded":

name=test&streets%5B1%5D=A01%2CA02%2CA03&streets%5B2%5D=A01%2CA02%2CA03

...i prettyed it for readability:

{
    "name": "test",
    "streets[1]": "A01,A02,A03",
    "streets[2]": "A01,A02,A03"
}

Thanks for support C:


Solution

  • I solved by putting

    $app->addBodyParsingMiddleware();
    

    I don't know why it works and how it really changes.

    https://stackoverflow.com/a/58827378/7336262