express body json code example
Example 1: body parser express
//make sure it is in this order
npm i body-parser
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.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})
Example 2: parse json express
// Update for Express 4.16+
// Starting with release 4.16.0, a new express.json() middleware is available.
var express = require('express');
var app = express();
app.use(express.json());
app.post('/', function(request, response){
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
app.listen(3000);
Example 3: node express post request json
var express = require('express');
var app = express();
app.use(express.json()); // built-in middleware for express
app.post('/', function(request, response){
let myJson = request.body; // your JSON
let myValue = request.body.myKey; // a value from your JSON
response.send(myJson); // echo the result back
});
app.listen(3000);
Example 4: express json body
$ npm install body-parser
Example 5: app use body parser
// parse application/json
app.use(bodyParser.json())