xxxxxxxxxx
const express = require('express')
const app = express()
app.use(express.json())
app.use(express.urlencoded())
xxxxxxxxxx
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))
})
xxxxxxxxxx
/** @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}`));
xxxxxxxxxx
// Express v4.16.0 onwards
const express = require('express');
// ---
app.use(express.json());
// Before Express v4.16.0
const express = require('express');
const bodyParser = require('body-parser');
// ---
app.use(bodyParser.json());
xxxxxxxxxx
SO HERE IS WHY WE USE IT:::
Body-parser parsed your incoming request, assembled the chunks
like containing your form data, then created this body object for you and
filled it with your form data.
Otherwise data will come in chunk's and it will become very difficult
to manage that data one by one so it's better to store all data in a
single object and than work on that object.