node-formidable / formidable

The most used, flexible, fast and streaming parser for multipart form data. Supports uploading to serverless environments, AWS S3, Azure, GCP or the filesystem. Used in production.
MIT License
7k stars 680 forks source link

many properties from Fields return array despite of the FormData didn't append any array #876

Closed demosofa closed 1 year ago

demosofa commented 1 year ago

Support plan

Context

What are you trying to achieve or the steps to reproduce?

In the browser, I have data is an object whose each property contains only a value as a type string. I use FormData to append those properties. There isn't any duplicate property in the request payload. But when console.log the property in the fields from parseForm function, I got an array with a length equal to 1

import { IncomingForm, Fields, Files, Options } from "formidable";
import { NextApiRequest } from "next";

export default function parseForm(req: NextApiRequest, options: Partial<Options> = {
  multiples: true,
  keepExtensions: true,
}) {
  const form = new IncomingForm(options);
  return new Promise<{fields: Fields, files: Files}>((resolve, reject) => {
    form.parse(req, (error, fields, files) => {
      if (error) reject(error);
      resolve({ fields, files });
    });
  });
}

What was the result you got?

[ 'CMS/store/test_id' ]

What result did you expect?

'CMS/store/test_id'

GrosSacASac commented 1 year ago

It is not a bug it is a feature. It is always an array to avoid type error based on different user input.

To have a single value use the provided firstValues function:


import { IncomingForm, Fields, Files, Options } from "formidable";
import { firstValues } from "formidable/src/helpers/firstValues.js";
import { NextApiRequest } from "next";

export default function parseForm(req: NextApiRequest, options: Partial<Options> = {
  multiples: true,
  keepExtensions: true,
}) {
  const form = new IncomingForm(options);
  return new Promise<{fields: Fields, files: Files}>((resolve, reject) => {
    form.parse(req, (error, fields, files) => {
      if (error) reject(error);
      resolve({ fields: firstValues(form, fields), files });
    });
  });
}