[Cakephp 4]Fetch API send CSRF give me 400 error

Hello,

I am trying to send a POST request to my controller (without form). For that, I use fetch API with this code :
var data = {
“action”: e.target.getAttribute(‘data_action’),
“username”: e.target.getAttribute(‘data_username’)
}
let response = fetch(’/website/follow/request’, {
headers: {
“X-Requested-With”: “XMLHttpRequest”,
“X-CSRF-Token”: csrfToken
},
method: “POST”,
credentials: “same-origin”,
body: JSON.stringify(data)
})
.then(function(response) {
return response.text();
})
.then(function(Data) {}
}

Following the DOC,the token is defined like this

echo $this->Html->scriptBlock(sprintf(
'var csrfToken = %s;',
json_encode($this->request->getAttribute('csrfToken'))

));

After sending my request, i GET an error 400 with ‘_Token’ was not found in request data.

If I look at the header of the request sent through the browser, I can see that the csrf is sent

How can I correctly send the token to the controller to make my request ?

Thanks

The _Token field is used by SecurityComponent/FormProtectionComponent and not CSRF. If you have either of those components active and want to submit requests via fetch() you’re going to have a hard time. Both of these components hash the fields & and hidden input values in a form and require that hash to be present when processing POST data. You’ll either need to extract that data out of the HTML form created with FormHelper, or disable those components for the actions you want to submit data to via fetch().