1
votes

I want to send a images folder along with the other data. (name and openingHours);

this is my vuejs code that I use to submit data to the backend

const formData = new FormData();

formData.append("name", this.name);
formData.append("openingHours", this.openingHours);
formData.append("photos", this.selectedFile);

await this.$http.post("spa", formData);

enter image description here

Here my controller code

var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
router.post('/', upload.array('photos', 10), async (req, res) => {

  console.log(req.file);
  console.log(req.body);


});

Here the req.file is undefined and photos also come under the body and also this openingHours is not an array. I pass and array in the front-end.

enter image description here

This is my body parser settings in the app.js

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());

Can anybody tell me what's wrong with my code?

I want to pass openingHours as an JS array.

UPDATED this is what I get if I console log openingHours in that method. enter image description here

1
Show the Vue component definition. What is this.openingHours and what is it bound to? - Mat J
If there is a file is involved, you must pass the body as multipart/form-data and hence you cannot pass json in there as it is a different format. You can pass json as string and manually parse it in server side. - Mat J

1 Answers

0
votes

You need to stringify your array calling JSON.stringify before saving to FormData:

formData.append("openingHours", JSON.stringify(this.openingHours));

And on the backend you need to parse it calling JSON.parse:

const openingHours = JSON.parse(req.body.openingHours)