Wednesday, March 16, 2022

[FIXED] $this->request->getData() empty after upgrade to CakePHP 4.0

Issue

After upgrading to CakepPHP 4.0 my POST request trough XMLHttpRequest stopped passing data to $this->request->getData()

The data is accesible by $this->request->input('json_decode'); though and GET requests work as well.

But I wonder what has changed in comparision to 3.* and why it's not working like it was before.

This is my xhr:

this.$http.post(
            url, 
            data, 
            {headers: {'X-CSRF-TOKEN': '<?= $this->request->getAttribute('csrfToken') ?>'}}, 
            })
            .then(response => {
                //
            }
        );

It gives me an empty array when I call $this->request->getData()

I tried to turn off FormProtection component for that specific action but nothing changed.


Solution

If want to know what changed, check the out the migration guide first, in this case specifically the breaking changes section for components.

The request body parsing features have been removed from the request handler component (the deprecation warning that was in place previously has been removed too, as it was causing too many false positives). This should now be handled by the body parser middleware, which you need to add your application accordingly, either globally in your Application class':

public function middleware(MiddlewareQueue $middlwareQueue): MiddlewareQueue
{
    // ...

    $middlwareQueue->add(new \Cake\Http\Middleware\BodyParserMiddleware());  

    return $middlwareQueue;
}

or in a routing scope:

\Cake\Routing\Router::scope('/', function (\Cake\Routing\RouteBuilder $routes) {
    $routes->registerMiddleware('bodyParser', new \Cake\Http\Middleware\BodyParserMiddleware());
    $routes->applyMiddleware('bodyParser');

    // ...
});

See also



Answered By - ndm

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.