Categories
JavaScript Answers

How to parse form data request with Express.js and JavaScript?

Spread the love

Sometimes, we want to parse form data request with Express.js and JavaScript.

In this article, we’ll look at how to parse form data request with Express.js and JavaScript.

How to parse form data request with Express.js and JavaScript?

To parse form data request with Express.js and JavaScript, we can use the body-parser package.

To install it, we run

npm i body-parser

Then we write

//...

const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(bodyParser.urlencoded({ extended: true }));

app.post("/post", (request, response) => {
  console.log(request.body);
  res.send("ok");
});

//...

to add

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

so that we can parse form data request bodies and make them available with request.body in the route handler.

We use request.body in the route handler for the /post route to get the form data request body as an object.

Conclusion

To parse form data request with Express.js and JavaScript, we can use the body-parser package.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.