Home > Software engineering >  Javascript object is devoid of property after axios post request
Javascript object is devoid of property after axios post request

Time:11-30

I am making a web app with VueJS that makes axios calls to a NodeJS API that uses express. I'm currently trying to send files to my NodeJS so it can save them. However, even though my browser displays all the properties of my array of files, my NodeJS reads it as empty. I've read all the questions previously asked on this topic but I haven't made any progress whatsoever. Note that I can POST any other data just fine, all my SQL Insert requests do well, mind you they don't involve sending arrays.

Example of promising solution that did not work : https://stackoverflow.com/a/66541165/12498040

Here is my client side JS, console.log() prints an array of N files object in the browser console :

    console.log(data)
    await axios.post('/api/fichiers', {fichiers:data});

Here is my NodeJS, with console.log(element) it prints N number of "{}" in the browser console and console.log(element.name) prints N number of "undefined" in the server terminal :

app.post('/api/fichiers', (req, res) => {
  req.body.fichiers.forEach((element) => {
    console.log(element.name);
  });
});

Thank you for any help you could provide :)

CodePudding user response:

You are getting an array of empty objects because File objects are not serializable to JSON.

If you want to send files, you need to replace the object containing a plain array you are passing to axios (which it will try to serialize to JSON) with a FormData object.

Then you need body parsing middleware in your Express application which can handle the multipart/form-data request body that a FormData object will generate. The body-parser module can't do that, but its documentation links to a number of options.

  • Related