YoussefElManssouri
YoussefElManssouri

Reputation: 53

NodeJS Request error sending multipart/form-data

I'm using a Node.js app as proxy for a webservice. I'm able to transfer simple application/json request with body-parser but it cant handle multipart/form-data.

To do so, I'm trying to use the request module but I have an error when I attach files to the request :

Error: write after end
    at ClientRequest.OutgoingMessage.write (_http_outgoing.js:413:15)
    at Request.write(./node_modules/request/request.js:1362:25)

Here's the code that triggers this error :

var form_data = {};

            for (var key in req.files){
                form_data[req.files[key].fieldname] = fs.createReadStream(req.files[key].path);
                log.debug("File :", req.files[key].fieldname)
            }

            var multipart_request = request_module({
                url: 'http://example.com',
                method: ‘POST’,
                headers: req.headers,
                body: JSON.stringify({<some content here>}),
                formData: form_data
            }, function(error, response, body){

                if(error){
                    log.debug(error);
                    res.status(500).send('{"message": "Server error.}');
                }
                else{
                    res.status(response.statusCode).send(body);
                }

            });

Is an other solution to do that ?

Upvotes: 2

Views: 2617

Answers (1)

mscdex
mscdex

Reputation: 106698

If you supply form or formData, you cannot also have body in your request options.

Upvotes: 4

Related Questions