#FormData is an empty object in backend

16 messages · Page 1 of 1 (latest)

sly sonnet
#

What happens if you console.log(formData) inside the addHotelApiCall function? Is the form data correct there?

#

Also in your endpoint what is "verify token"? Could that be removing the body from the request? @sterile badger

sterile badger
#

Yes, it returns a FormData {} instance. If i iterate over it, it returns the correct keys and vals

true tapir
#

hey @sterile badger

#

I do not have much experience in express server.

#

As far as i know from the other backend language, if you're sending form data to any API, then use {headers: {'Content-Type': 'multipart/form-data'}}

#

to handle the form data in backend, you can use "busboy" and "multer."

sterile badger
#

This is the API with multer

#

@true tapir Using {'Content-Type': 'multipart/form-date'} gives this Error: Multipart: Boundary not found

true tapir
#

but are trying to post data as json@sterile badger

true tapir
#

"busboy"
const busboy = Busboy({ headers: req.headers });
let sectionData = {};

  busboy.on("field", (fieldname, value) => {
    sectionData[fieldname] = value;
  });

  busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
    const tempFilePath = path.join(os.tmpdir(), filename.filename);
    file.pipe(fs.createWriteStream(tempFilePath));

    sectionData.image = {
      name: filename.filename,
      type: filename.mimeType,
      tempFilePath: tempFilePath,
    };
  });

  busboy.on("finish", async () => {
    try {
      const { image, folder, ...otherFields } = sectionData;
      const imgParams = {
        Bucket: "BUCKET NAME",
        Key:  image.name,
        Body: fs.createReadStream(image.tempFilePath),
        ContentType: image.type,
      };

      const imgURL = await s3.upload(imgParams).promise();

      await fs.unlinkSync(image.tempFilePath);
      return res.status(200).json(imgURL);
    } catch (error) {
      console.error("Error uploading file:", error);
      return res.status(500).json({ error: "Failed to upload file" });
    }
  });
#

if you still facing the same issue, then share the vs code live link and I will help you @sterile badger

sterile badger
#

@true tapir I can share the gitub repo with you, if that's fine