express.json req.body 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: 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 3: express json body
var bodyParser = require('body-parser')
Example 4: app use body parser
// parse application/json
app.use(bodyParser.json())