HTTP Post request from React using axios

Viewed 35

I am having issues sending post request to my server using Axios library.

The issue I am facing is that I have a couple of variables with JSON data that I need to send. I send them as parameters, then I get an error: Malformed HTTP request.

When I send them as form data, I cannot decode them on my server which is running Laravel. There type is shown as [object Object] on my server.

Here is my code:

http.js

export default axios.create({
    baseURL: "http://127.0.0.1:8000/api/",
    headers: {
        "Content-type": "application/octet-stream",
        "Authorization": "Bearer XXX"
    },
})

Controller.js

let formData = new FormData()

formData.append("smartBUOY", this.state.smartBUOY)
formData.append("smartQUMATIK", this.state.smartQUMATIK)

http.post(
    "generate/downloadReport",
    formData,
    {
        headers: {
            "Content-Type": "multipart/form-data"
        },
        responseType: 'blob',
        processData: false,
    }
)
    .then(response => {
        this.setState({
            downloadLoading: false
        })
    })

On my server running Laravel, I do:

$data = $request->get("smartBUOY");

$json_data = json_decode($data, true);

I get a null value. As I mentioned before, when I check the type of $data, it shows as [object Object].

I tried explicitly converting my data to Json format before sending it by using the following:

const jsonQUMATIK = JSON.stringify(this.state.smartQUMATIK)

And

const jsonQUMATIK = JSON.parse(this.state.smartQUMATIK)

But I still get the data on the server in the same [object Object] format and I don't know how to get the original data that I sent.

Thank you

1 Answers

I needed to serialize data before sending it. This worked for me:

const jsonQUMATIK = serialize(this.state.smartQUMATIK)
const jsonBUOY = serialize(this.state.smartBUOY)
formData.append("smartQUMATIK",jsonQUMATIK)
formData.append("smartBUOY",jsonBUOY)

On the server, I can json_decode it.

Related