express body-parser deprecated code example
Example 1: express bodyparser deprecated
The package bodyParser is deprecated. You will get this warning with these lines of code:
app.use(bodyparser.json());
app.use(bodyParser.urlencoded({extended: true}));
If you are using Express 4.16+ you can now replace those lines with:
app.use(express.json());
app.use(express.urlencoded());
Example 2: express bodyparser deprecated
body-parser has been deprecated from express v4.*
Use body-parser package instead.
npm i body-parser
import bodyParser from "body-parser";
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Example 3: express bodyparser
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const PORT = process.env.PORT || 3000;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
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 4: body-parser deprecated
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());