Why is req.busboy undefined?

I am using connect-busboy

Express.js 4 to upload files. I added app.use(busboy({ immediate: true });

to app.js. My route handler looks like this:

router.post('/upload', function (req, res) {
    var fstream;

    req.busboy.on('file', function (fieldName, file, fileName) {
        console.log('Uploading ' + fileName + '...');
        fstream = fs.createWriteStream(__dirname + '/data/' + fileName);
        fstream.on('close', function () {



returns undefined

. Why?!??!


source to share

2 answers

Sorted! It turns out that it contentType

should be form/multi-part

, which was not the case



For multipart forms:

Content-Type: multipart/form-data; boundary=----WebKitFormBoundary63SFlxFGGDbxCqT7


The borders are randomly generated to make this work in Node Express. It is recommended that this header be set to 'undefined', the browser will take care of the rest. For example:

        method: 'POST',
        url: 'http://youurl.com,
        data: data,
        // Remove the 'Content-Type' header for multipart form submission
        headers: { 'Content-Type': undefined },
    }).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
    }, function errorCallback(response) {
        // called asynchronously if an error occurs


For those who have the same question as Jordan:

"Could you be more specific. What type of content is that?"

This means setting the Content-Type header in the request sent from your browser to the web server. For example, setting the content type header to JSON looks like this:

Content-Type: application/json; charset=utf-8




All Articles