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:[email protected]: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.
You NEED express. json() and express. urlencoded() for POST and PUT requests, because in both these requests you are sending data (in the form of some data object) to the server and you are asking the server to accept or store that data (object), which is enclosed in the body (i.e. req.
So the difference is express. json() is a body parser for post request except html post form and express. urlencoded({extended: false}) is a body parser for html post form.
Express provides methods to specify what function is called for a particular HTTP verb ( GET , POST , SET , etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where template files are located, and what template to use to render a response.
Body-parser is the Node. js body parsing middleware. It is responsible for parsing the incoming request bodies in a middleware before you handle it.
bodyParser is in fact the composition of three middlewares (see documentation and relevant source code): json, urlencoded and multipart:
json parses application/json request bodiesurlencoded parses x-ww-form-urlencoded request bodiesmultipart 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With