node-formidable/formidable

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

demosofa opened this issue · 1 comments

Support plan

  • Which support plan is this issue covered by? (Community, Sponsor, Enterprise): Community
  • Currently blocking your project/work? (yes/no): yes
  • Affecting a production system? (yes/no): no

Context

  • Node.js version: v16.15.1
  • Release Line of Formidable (Legacy, Current, Next): Next
  • Formidable exact version: v3.2.4
  • Environment (node, browser, native, OS): NEXT.js (node)
  • Used with (popular names of modules): cloudinary

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'

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 });
    });
  });
}