ReactJS axios POST request send all options as a single JSON key with empty value

1.3k Views Asked by At

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));
3

There are 3 best solutions below

2
Dhaval Chheda On BEST ANSWER

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

2
Oluwafemi Sule On

The axios client is posting the request with Content-Type header of application/json and as a raw input stream of JSON payload.

Use CodeIgniter\HTTP\IncomingRequest::getJSON to grab this stream from the request body as parse it as JSON into an object.

$json = $this->request->getJSON();

// Access sample_key field from object
$json->sample_key;

You could also parse the request body into an associative array by passing true for the first parameter.

$json = $this->request->getJSON(true);

// Access 'sample_key' key in array
$json['sample_key'];
0
Waqar Akram On

Make you data object in such a way & then pass this object to post request.

let data = {sample_key: "sample_value"}

axios.post('http://localhost/exampleApiEndpoint', data)
.then(response => {
    // Do something
})

Thanks