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

No comments:

Post a Comment