1var bodyParser = require('body-parser')
2var app = express()
3
4// parse application/x-www-form-urlencoded
5app.use(bodyParser.urlencoded({ extended: false }))
6
7// parse application/json
8app.use(bodyParser.json())
1// If you are using Express 4.16+ you don't have to import body-parser anymore.
2// You can do it just like this:
3
4app.use(express.urlencoded({extended: true}));
5app.use(express.json()) // To parse the incoming requests with JSON payloads
1npm install body-parser
2// then in your app
3var express = require('express')
4var bodyParser = require('body-parser')
5
6var app = express()
7
8// create application/json parser
9var jsonParser = bodyParser.json()
10
11// create application/x-www-form-urlencoded parser
12var urlencodedParser = bodyParser.urlencoded({ extended: false })
13
14// POST /login gets urlencoded bodies
15app.post('/login', urlencodedParser, function (req, res) {
16 res.send('welcome, ' + req.body.username)
17})
18
19// POST /api/users gets JSON bodies
20app.post('/api/users', jsonParser, function (req, res) {
21 // create user in req.body
22})
23
1/* USE:
2
3npm i body-parser
4*/
5
6// then in your app
7var express = require('express')
8var bodyParser = require('body-parser')
9
10var app = express()
11
12// create application/json parser
13var jsonParser = bodyParser.json()
14
15// create application/x-www-form-urlencoded parser
16var urlencodedParser = bodyParser.urlencoded({ extended: false })
17
18// POST /login gets urlencoded bodies
19app.post('/login', urlencodedParser, function (req, res) {
20 res.send('welcome, ' + req.body.username)
21})
22
23// POST /api/users gets JSON bodies
24app.post('/api/users', jsonParser, function (req, res) {
25 // create user in req.body
26})