Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

form.parse() method is not invoking in node.js

I am using the formidable package to handle file uploads on my server. This is my express.js app code:

var formidable = require("formidable"),
  http = require("http"),
  util = require("util");
app.post("/admin/uploads", function (req, res) {
  console.log(req.files, req.fields); //It prints
  var form = new formidable.IncomingForm();
  form.parse(req, function (err, fields, files) {
    console.log("Inside form parse."); //its not printing
    console.log(err, fields, files); //its not printing
  });
  form.on("file", function (name, file) {
    console.log("file=" + file);
  }); //its not printing
  form.on("error", function (err) {
    console.log(err);
  }); //its not printing
  form.on("aborted", function () {
    console.log("Aborted");
  }); //its not printing
  console.log(form); //it prints
});

In the above code, the form.parse and form.on callbacks are never run. How can I solve this issue?

like image 564
R J. Avatar asked Nov 15 '12 13:11

R J.


3 Answers

It might be that you need to remove body parser

delete app.use(express.bodyParser());
like image 192
Marwan Roushdy Avatar answered Nov 11 '22 05:11

Marwan Roushdy


I had the same problem when using Next.js API routes with Formidable. Like the other answer points out, you have to remove the body parser. In Next.js, you can export a config object and disable body parsing.

// /pages/api/form.js
import { IncomingForm } from "formidable";

export default function handler(req, res) {
  // formidable logic
}

// VV important VV
export const config = {
  api: {
    bodyParser: false,
  },
};
like image 20
Jacob Avatar answered Nov 11 '22 07:11

Jacob


Call form.parse(...) after all on(...) events.

app.post('/admin/uploads', function(req, res) {
    var form = new formidable.IncomingForm(); 
    form.on('file', function(name, file) { });
    form.on('error', function(err) { });
    form.on('aborted', function() { });
    form.parse(req, function(err, fields, files) { });
});
like image 1
jerone Avatar answered Nov 11 '22 05:11

jerone