Home > Enterprise >  Axios post-request doesn't send complete object
Axios post-request doesn't send complete object

Time:02-11

I need to send an object including a base64-encoded image to an API-endpoint in TS. I use this code to convert a file to Base64 and attach it to an object:

const file = values.beleg1;
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = async function () {
                    const result = reader.result.toString().split(',')[1];
                    await valuesObj.push({ name: 'base64Image', value: result });

                };
                reader.onerror = function (error) {
                    console.log('Error: ', error);
                };

If I then log the object 'valuesObj' it does show that the base64-object is attached to the main-object. Screenshot of the logged object

However when I then I then use this object in the request like in the code below it is not shown in the payload when looking at the network-request

axios({
                url: 'http://localhost:8080/createPDF',
                method: 'POST',
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
                responseType: 'blob',
                data: valuesObj,
            })
                .then((response: AxiosResponse) => {
                    setLoadingText('');
                    const blob: Blob = new Blob([response.data], { type: 'application/pdf' });
                    const objectUrl: string = window.URL.createObjectURL(blob);
                    window.open(objectUrl);
                })
                .catch((error) => {
                    console.log(error);
                });

Screenshot of the network-payload

What is the reason for this? Does it have anything to do with the length/size of the string? Or is there another reason?

CodePudding user response:

Maybe this could be an issue linked to the size of the request you're sending.
Try to change the values for the Axios config of this property to see if something changes:

  // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
  maxBodyLength: 2000,

(reference: https://axios-http.com/docs/req_config)

CodePudding user response:

Your Problem seems to be that your async axios request gets the value of your valuesObj, before onl oad actually adds your new record.

Sorry forgot a solution ^^

Either you put your axios request directly into the pipe or you create another async function which you can call from your on.load function, which awaits both async events.

CodePudding user response:

Read this. It's typical of Jtards. I've seen so many bad cases of this. Is this yet another Jtard who writes very bad documentations or am I missing something?

  • Related