1

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.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
danny3b
  • 313
  • 5
  • 17

1 Answers1

2

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

ndm
  • 59,784
  • 9
  • 71
  • 110