Search code examples
javascriptnode.jsreactjsnext.jsform-data

How to fix bad request error while sending formdata to api in nodejs?


I'm getting the files to upload and other information using useform. and I log the information I receive to the screen and it does not come up null or undefined. it seems to be working correctly. but I could not send to api side. I get either 500 error or 400.

FRONTEND:

//index.js
function uploadFile(form) {

    const { email, description, files } = form;
    const formData = new FormData();
    Array.from(files).forEach((file) => {
        formData.append(file.name, file);
    });
   formData.append("email", email);
   formData.append("token", token)

   for (var key of formData.entries()) {
       console.log(key[0] + ", " + key[1]);
   }

   dispatch(uploadChallengeThunk(formData));

}

//service.js
export async function uploadChallengeService(formData) {
  Array.from(formData).forEach((item) => {
    console.log("🚀 ~ file: index.js:5 ~ Array.from ~ item", item);
  });
  return await api.post("/challenges/upload", formData);
}

BACKEND:

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

const formidableConfig = {
  multiples: true,
  allowEmptyFiles: false,
  maxFileSize: 5 * 1024 * 1024,
  keepExtensions: true,
  filename: (name, ext, part, form) => {
    return part.originalFilename;
  },
};

function parseRequest(req) {
console.log("not coming here");
  return new Promise((resolve, reject) => {
    const form = new formidable.IncomingForm(formidableConfig);

    form.parse(req, (error, fields, files) => {
      if (error) {
        alert("not working");
        console.log("not coming here");
        reject(new BusinessError(error.message, error.httpCode));
      }

      resolve({ files, fields });
    });
  });
}

async function postChallengesUpload(req, res) {
console.log("not coming here");
  const { files, fields } = await parseRequest(req);
}

export default apiHandler({
  POST: postChallengesUpload,
});

Solution

  • Your apiHandler is not working as you expect it to work, that is your core issue. The fact that you get 500's and 400's is a good sign that you're actually sending the request to your backend.

    When you get a 500 you typically caused an error that you didn't catch properly and it bubbled up too far. Typically called an Internal Server Error.

    You typically get 400's when you send something wrong, too small, too large, etc.

    The bright side is you are not getting a 404.

    You need to look at your apiHandler and make sure you set it up properly. Your server is giving back status codes, aka responses, but your apiHandler is not behaving the way you intend it to.