Express body-parser middleware

Express body-parser middleware

const express = require("express");
const bodyParser = require("body-parser");

const app = express();



// Automatic parsing
app.use(bodyParser.urlencoded({ extended: false })); // or bodyParse.json()// 

// or

// Manual parsing
app.use(function (req, res, next) {
  let body = "";
  req.on("end", () => {
    const userName = body.split("=")[1]; //["username","omar"]
    if (userName) {
      req.body = { name: userName };
    }
    next();
  });
  req.on("data", (chunk) => {
    body += chunk;
  });
});

Now this will parse all incoming requests and try to extract any data which is in your body if it's of type urlencoded data which be the case for such a submitted form. it will aslo call next for us, so it will also automatically move on to middlewares after this.

app.use(bodyParser.urlencoded({ extended: false }));

There is any benefits when we use bodyParser.json() instead of express.json()?

I still use it because in the past, you needed that extra package. If Express ever decides again to remove it from the its built-in features, the code still works.

Just a heads up, bodyparser is now deprecated so using express.json() is the best solution.

app.use(express.json()); //json data
//or
app.use(express.urlencoded({extended:false})); //form data
const express = require("express");
const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));

app.post("/user", (req, res, next) => {
  return res.send("<h1>User: " + req.body.username + "</h1>");
});

app.get("/", (req, res, next) => {
  res.send(
    `<form action="/user" method="POST">
    <input type="text" name="username"
    ><button type="submit">Create User</button></form>`
  );
});

app.listen(5000);