Utilizing Next.js with formidable for efficient parsing of multipart/form-data

I've been working on developing a next.js application that is supposed to handle multipart/form-data and then process it to extract the name, address, and file data from an endpoint.

Although I attempted to use Formidable library for parsing the formdata object, I'm encountering difficulties in making it function properly. The fields and file values are all showing up as empty objects {}. Are there any recommendations or tips on how to effectively parse the form data?

export default function supplier(req, res) {
  if (req.method == 'POST') {
    //console.log("req: \n",req);
    console.log("req body: \n",req.body);
    //console.log("req.file: \n",req.headers);
    //console.log("req.address: \n",req.body.address);
    
    const form = new formidable.IncomingForm();
    //console.log("form: \n",form);
    //const form = new multiparty.Form();
    let FormResp = new Promise((resolve,reject)=>{
      form.parse(req, (err, fields, files)=>{
          console.log("fields: ",fields);
          console.log("files: ",files);
          //await saveFile(files.file);
          //await saveDB();
          return res.status(201).send("");
      });
    });
  } else {
    // Handle any other HTTP method
    return res.status(405).json({ error: `Method '${req.method}' Not Allowed` });
  }

const handleSubmit = async (event) => {
    event.preventDefault();

    const formdata = new FormData();
    const json = JSON.stringify({"name":event.target.name.value, "address":event.target.address.value, "file": createObjectURL})
    
    formdata.append("file", image);
    formdata.append("name", event.target.name.value);
    formdata.append("address", event.target.address.value);
    console.log("formdata: \n", formdata);

    //var request = new XMLHttpRequest();
    //request.open("POST", "/api/supplier");
    //request.send(formData:body);

    const response = await fetch("/api/supplier",{method: 'POST', body: formdata, "content-type":"multipart/form-data"});

    //const result = await response.json()
    //console.log(result)
    
};

------WebKitFormBoundaryiu8apU5i3hWyORTY
Content-Disposition: form-data; name="name"

Hello
------WebKitFormBoundaryiu8apU5i3hWyORTY
Content-Disposition: form-data; name="address"

addressssssssss
------WebKitFormBoundaryiu8apU5i3hWyORTY--

req body: 
 ------WebKitFormBoundary92WJpSOKb0mEfOAH
Content-Disposition: form-data; name="file"; filename="attachment.svg"
Content-Type: image/svg+xml

<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 48 48" viewBox="0 0 48 48"><path d="M35.5,34V16c0-0.83-0.67-1.5-1.5-1.5s-1.5,0.67-1.5,1.5v18c0,4.69-3.81,8.5-8.5,8.5s-8.5-3.81-8.5-8.5V11
        c0-3.03,2.47-5.5,5.5-5.5s5.5,2.47,5.5,5.5v21.5c0,1.38-1.12,2.5-2.5,2.5s-2.5-1.12-2.5-2.5V13c0-0.83-0.67-1.5-1.5-1.5
        s-1.5,0.67-1.5,1.5v19.5c0,3.03,2.47,5.5,5.5,5.5s5.5-2.47,5.5-5.5V11c0-4.69-3.81-8.5-8.5-8.5s-8.5,3.81-8.5,8.5v23
        c0,6.34,5.16,11.5,11.5,11.5S35.5,40.34,35.5,34z"/></svg>
------WebKitFormBoundary92WJpSOKb0mEfOAH

Answer №1

Were you referring to multipart/form-data in your original query?

If you're encountering issues using formidable in Next.js, a workaround is to turn off the default body parser. You can achieve this by exporting a configuration object from your API route and setting api.bodyParser to false. This will maintain the request stream as-is so that formidable can correctly parse it.

To implement this workaround, simply include the following lines of code:

export const config = {
  api: {
    bodyParser: false,
  },
}

export default async function yourRoute(
  req: NextApiRequest,
  res: NextApiResponse
) { }

Answer №2

It may seem like it's too late to mention, but avoid trying to directly return res inside a Promise. Instead, resolve the promise first and then send the response based on the output.

export default function supplier(req, res) {
  if (req.method !== 'POST') {
    // Handle any other HTTP method
    res.status(405).json({ error: `Method '${req.method}' Not Allowed` });
    return;
  }
    
  let FormResp = new Promise((resolve,reject) => {
    const form = formidable();
    form.parse(req, (err, fields, files)=>{
      if (err) reject(err);
      else resolve({ fields, files });
    });
  });

  const { fields } = FormResp;
  console.log(fields);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a string specifically for implementing regular expressions in JavaScript

I'm currently working on a custom jQuery plugin known as jQuery-Faker. This plugin is designed to produce fake data for populating form fields based on their respective field names. One of the tasks I have set out to accomplish is generating phone num ...

How to delete the last item of an array in AngularJS using scope

In my Angular controller, I have an array and a method for deleting objects. function($scope, $http){ $scope.arrayOfObjects = []; $scope.remove = function(obj){ var i = $scope.arrayOfObjects.indexOf(obj); if( i > -1 ){ ...

Ways to generate multiple instances using create-next-app

I'm currently using this tool to help me develop a Next app: Encountering the following issue: create-next-app --example with-next-i18next with-next-sass with-next-seo next-learn An error occurred. The example named "with-next-i18next" could not be ...

Module Express - Transferring Object to Main Application

Having issues with passing an object in Express from a module to my application. The process is straightforward - gathering input from a form, validating the string, and returning either null or an object. Despite trying various methods, I'm still fac ...

The $resources headers have not been updated

My objective is to include a header with each HTTP request for an ngResource (specifically, an auth token). This solution somewhat accomplishes that: app.factory('User', ['$resource','$window', function($resource,$window,l ...

The Wikipedia API is unable to be loaded using the XMLHttpRequest

I have encountered this error before on this platform, and although I managed to fix it, I am seeking a more in-depth explanation of the solution. For a project where I am learning, I decided to create a Wikipedia Viewer application. The first step was to ...

When converting a .ts file to a .js file using the webpack command, lengthy comments are automatically appended at the end of

As a backend developer, I recently delved into UI technologies and experimented with converting TypeScript files (.ts) to JavaScript files (.js) using the webpack command. While the conversion works well, the generated .js file includes lengthy comments at ...

Tips for enabling the background div to scroll while the modal is being displayed

When the shadow view modal pops up, I still want my background div to remain scrollable. Is there a way to achieve this? .main-wrapper { display: flex; flex-direction: column; flex-wrap: nowrap; width: 100%; height: 100%; overflow-x: hidden; ...

Infinite Scrolling in React: Troubleshooting Issues with the dataLength Parameter

A function called newsFeed is utilized within the useEffect hook to make a request to an endpoint for fetching posts made by the logged in user and users they follow. The retrieved data is then saved to the state: const [posts, setPosts] = useState([]) con ...

React Router: Dispatch not triggering when route changes

I have multiple paths that share the same controller: <Route component={Search} path='/accommodation(/:state)(/:region)(/:area)' /> and when the route changes, I trigger the api function within the component: componentWillReceiveProps = ...

Issues arise when Angular properties become undefined following the initialization or OnInit functions

There seems to be a peculiar issue with the properties of an angular component that I have set up. It appears that these properties are losing their values after the initialization process. The component is essentially a basic HTML file containing a video ...

Customize dynamically loaded data via AJAX

I have a webpage that is loading a table from another source. The CSS is working fine, but I am facing an issue editing the table using jQuery when it's loaded dynamically through a script. It seems like my changes are not getting applied because they ...

Unique rewritten text: "Displaying a single Fancybox popup during

My website has a fancybox popup that appears when the page loads. I want the popup to only appear once, so if a user navigates away from the page and then comes back, the popup should not show again. I've heard that I can use a cookie plugin like ht ...

Is it possible to integrate the Firestore npm library into my Express application?

Recently, I created my own library to act as a nosql database on my node.js web server in place of mongodb. I came across this interesting quote: Applications that use Google's Server SDKs should not be used in end-user environments, such as on pho ...

How to Effortlessly Populate Cascading Dropdowns in ASP.Net MVC 5 using a Reusable

I am currently working on an ASP.Net MVC 5 application that has multiple edit pages. Each edit page consists of various input elements such as textboxes, checkboxes, and dropdowns. I want to implement a functionality where the values of one dropdown are ch ...

What is the best approach to removing a component by utilizing the children prop in React?

I am currently working on a specific scenario: In my project, I have a component called Foo with a property named bar If the bar property is set to true, then I need to display the Bar component that is nested inside the Foo component If the bar prop ...

Please ensure that the table is empty before reloading data into it

I am facing an issue while binding data from the database. The data is being bound every 5 seconds, however, it does not clear the previous data and keeps accumulating. Instead of displaying just 3 rows when there are 3 in the database, it adds 3 rows ev ...

javascript search for parent function argument

I am struggling to figure out how to locate the key in my json array. When I try to find the key using a function parameter, it does not seem to work. This is a snippet of my json data: ... { "product": [ { "title": " ...

Using Ajax without implementing JavaScript

Is it possible to develop an application that utilizes Ajax without relying on JavaScript, allowing it to function even if JavaScript is disabled by the user in their browser? Are there any restrictions or limitations to consider? ...

Guide on downloading a PDF file with NodeJS and then transmitting it to the client

My goal is to download a PDF file using NodeJS and then send its data to the client to be embedded in the page. Below is the code snippet I am using to download the PDF file: exports.sendPdf = function(req, responce) { var donneRecu = req.body; va ...