Thursday, 1 August 2019

Express: body-parser: hello World application


Step 1: Create new package bodyParserDemo.

Step 2: navigate to ‘bodyParserDemo’ and execute the command ‘npm init’.
It prompts you for the basic information and create package.json file.

package.json
{
  "name": "bodyparserdemo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Step 3: install express dependency by executing the command ‘npm install express’.

Step 4: Install body-parser dependency by executing the command ‘npm install body-parser’.
package.json file is changed like below.


package.json
{
  "name": "bodyparserdemo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.3",
    "express": "^4.16.4"
  }
}

Step 5: Create index.js like below.


index.js

const express = require('express')
const bodyParser = require('body-parser')
 
const app = express()
 
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
 
// parse application/json
app.use(bodyParser.json())

app.get('/', (req, res) => {
 res.send('Hello World')
})
 
app.post('/user', (req, res) => {
  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:\n')
  res.end(JSON.stringify(req.body, null, 2))
})

const port = 3000
app.listen(port, () => console.log(`Application started listening on port ${port}!`));

Run index.js

Hit below request from any rest client like postman.

Method: POST

headers:
Content-Type : application/json

Body:
{
         "name" : "Krishna",
         "age" : 29
}


When you hit the request, you will receive below kind of response.



Previous                                                    Next                                                    Home

Introduction to body-parser


‘body-parser’ package provides a middleware that is used to parse the request body before handling it over to the actual router.

Is body-parser handles multi-part requests?
No, to handle multi-part request use one of following packages.
a.   busboy and connect-busboy
b.   multiparty and connect-multiparty
c.    formidable
d.   multer

What are the parsers provided by body-parser?
a.   JSON body parser
b.   Raw body parser
c.    Text body parser
d.   URL-encoded form body parser




Previous                                                    Next                                                    Home

body-parser tutorial

Previous                                                    Next                                                    Home