express body-parser 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: urlencoded json express
var express = require('express')
var app = express()
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
app.post('/profile', function (req, res, next) {
console.log(req.body)
res.json(req.body)
})
Example 3: body parser npm
var bodyParser = require('body-parser')
Example 4: express bodyparser
/** @format */
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const PORT = process.env.PORT || 3000;
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
//connecting to db
try {
mongoose.connect('mongodb://localhost/YOUR_DB_NAME', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
}, () =>
console.log("connected"));
} catch (error) {
console.log("could not connect");
}
app.get("/", (req, res) => {
res.send("home");
});
app.listen(PORT, () => console.log(`Server is listening on port ${PORT}`));
Example 5: express bodyparser
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 6: body parser npm
const jsonParser = bodyParser.json()
const urlencodedParser = bodyParser.urlencoded({ extended: false })