I am using ReactJS in the frontend and making a POST request to a CodeIgniter4 backend.
My frontend call looks like this -
axios.post('http://localhost/exampleApiEndpoint', { sample_key: 'sample_value' })
.then(response => {
// Do something
})
If I run the following code -
$this->request->getPost('sample_key');
I expect it to return 'sample_value' but I get null
So I decided to run the following code in CI4 to see what is happening in the background
$this->request->getRawInput()
it returns {{"hello":"world"}: ""}
And sure enough when I run $this->request->getPost('{"hello":"world"}');
it gives me empty string (no null, but empty string)
I am new to both frameworks. I am not entirely sure how to proceed further from this point. I used the following snippet as a workaround which works as long as there are no symbols in the input. If there are any, they are converted to underscore. Which is less than ideal.
$raw_input = $this->request->getRawInput();
$json_input = json_decode(array_key_first($raw_input));
Axios sends the data in the format of JSON Body while sending the data to the API. In order for you to send the data as a POST, you have to use FormData API.
let formData = new FormData();
formData.append('sample_key','sample_value');
Than Send this FormData object instead of the Javascript Object that you are sending:
axios.post('http://localhost/exampleApiEndpoint', formData)
.then(response => {
// Do something
})
In the CI4 Controller you can get your data by following :
$data = $this->request->getPost();
Reference: https://developer.mozilla.org/en-US/docs/Web/API/FormData