Search code examples
reactjsnext.js

FormData with NextJS API


I am trying to create a simple CRUD application using NextJS along with react-redux, so what it does is that it saves peoples contacts.So when adding a contact i am trying to send some data along with a file to a NextJS API.

Issue

ContactAction.js

Make a POST request from redux action to add a contact

export const addContact = (data) => async (dispatch) => {
 try {
      var formData=new FormData();
      formData.append('name',data.Name);
      formData.append('email',data.Email);
      formData.append('phone',data.Phone);
      formData.append('image',data.Image);
      let response= await Axios.post(`http://localhost:3000/api/contact/addContact`,formData,{
         headers:{
             'x-auth-token':localStorage.getItem('token')
         }
      });
   } catch (error) {
       console.log(error);
   }
}

addContact.js

This is the API route in /api/contact/

  const handler = async (req, res) => {
   switch(req.method){
    case "POST":{
       await addContact(req,res)
       }
     }
   }
   const addContact = async  (req, res) => { 
     console.log(req.body);
    // do some stuff here and send response
   }

this is what i get in the terminal after the log,also the file is Gibberish as well when logging req.files

enter image description here

Current effort

I tried using third party packages such as formidable and formidable-serverless but got no luck. so after a day i made it work with a package called multiparty.

addContact.js

  const handler = async (req, res) => {
   switch(req.method){
    case "POST":{
      let form = new multiparty.Form();
      let FormResp= await new Promise((resolve,reject)=>{
       form.parse(req,(err,fields,files)=>{
        if(err) reject(err)
        resolve({fields,files})
        });
      }); 
      const {fields,files} = FormResp;
      req.body=fields;
      req.files=files;
       await addContact(req,res)
       }
     }
   }
   const addContact = async  (req, res) => { 
     console.log(req.body); //Now i get an Object which i can use
    // do some stuff here and send response
   }

The above solution is obviously redundant and probably not the best way to go about it plus i don't want to add these 7 8 lines into each route.

what am i doing wrong? why formData doesn't seem to work with NextJS API (when it works with the Express server)?


Solution

  • FormData uses multipart/form-data format. That is not a simple POST request with a body. It is generally used for uploading files, that's why it needs special handling. As an alternative, you could use JSON.