3

i am passing an array to formdata but getting it as string. How can i save it in array only.

tags=["abc", "def", "ghi"]
formData.set("tags",tags);

if i do this at frontend then nothing is getting save at backend

const clickSubmit = (event) => {
    event.preventDefault();
    setValues({ ...values, error: "", loading: true });
    tags.forEach((tag) => formData.append("tags[]", tag));
    createProduct(formData).then((data) => {
      if (data.error) {
        setValues({ ...values, error: data.error });
      } else {
        setValues({
          ...values,
          name: "",
          description: "",
        });
      }
    });
  };

the backend code after submitting form

exports.create = (req, res) => {
  console.log("REQ", req.body);
  let form = new formidable.IncomingForm();
  form.keepExtensions = true;
  form.parse(req, (err, fields, files) => {
    if (err) {
      return res.status(400).json({
        error: "Image could not be uploaded",
      });
    }
    let product = new Product(fields);
    console.log("P", product);

    if (files.photo) {
      product.photo.data = fs.readFileSync(files.photo.path);
      product.photo.contentType = files.photo.type;
    }

    product.save((err, result) => {
      if (err) {
        return res.status(400).json({
          error: errorHandler(err),
        });
      }
      res.json(result);
    });
  });
};

also the req.body giving empty object,why so i have use

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
1
  • You cannot set an array value in formData. Read the docs. Commented Apr 24, 2021 at 20:00

1 Answer 1

4

this is not how we pass an array to formData. you have to loop through all the array items and add them to formData one by one.

const frmData = new FormData();
const tags = ["abc", "def", "ghi"];
tags.forEach(tag => frmData.append('tags[]', tag))

So the takeaway here is that when you want to add an array to form data you have to use key name as "key[]" with the array symbol at the end.

Sign up to request clarification or add additional context in comments.

5 Comments

Doing this no data gets added in the form data
try seeing the formData using frmData.getAll('tags[]')
It's showing all but nothing is passed while saving the data in DB
then there must be something wrong with the backend
I have added the backend above, please check

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.