Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

Express (or Connect's) bodyParser middleware is marked deprecated and users are advised to use instead:

app.use(connect.urlencoded())
app.use(connect.json())  

However, when I run the an example from Node.js in Action, I use curl to fill out the form as suggested by the book:

curl -F entry[title]='Ho ho ho' -F entry[body]='santa loves you' http://abc:123@127.0.0.1:3000/api/entry

It doesn't work. req.body is not defined. Am I missing something? It works fine with bodyParser.

EDIT: SOLUTION as of Express 4

Parse json this way:

var bodyParser = require('body-parser');

...

app.use(bodyParser.json());

Parse urlencoded body this way:

app.use(bodyParser.urlencoded({extended: true}));

Then there is no deprecation warning. The extended: true (default) uses the qs module and false uses the querystring module to parse the body.

Don't use app.use(bodyParser()), that usage is now deprecated.

share|improve this question
up vote 22 down vote accepted

bodyParser is in fact the composition of three middlewares (see documentation and relevant source code): json, urlencoded and multipart:

  • json parses application/json request bodies
  • urlencoded parses x-ww-form-urlencoded request bodies
  • and multipart parses multipart/form-data request bodies, which is what you're interested in.

If you only specify json and urlencoded middlewares, the form data won't be parsed by any middleware, thus req.body won't be defined. You then need to add a middleware that is able to parse form data such as formidable, busboy or multiparty (as stated in connect's documentation).

Here is an example, using multiparty:

var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
app.use('/url/that/accepts/form-data', multipartMiddleware);
app.post('/url/that/accepts/form-data', function(req, resp) {
    console.log(req.body, req.files);
});

Don't forget that by using such middlewares you allow anyone to upload files to your server: it then your responsibility to handle (and delete) those files.

share|improve this answer
    
Ah.. I should've read the source. Thanks. – huggie Mar 3 '14 at 11:37
2  
Oh, just noticed that multipart is deprecated as well. – huggie Mar 3 '14 at 12:15
1  
You can look into an alternative such as busboy or formidable then :) The API isn't exactly the same though – Paul Mougel Mar 3 '14 at 12:46
    
I've added a solution to the question. – huggie Sep 5 '14 at 2:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.