Categories
JavaScript Answers

How to get data passed from a form in Express and Node.js?

Spread the love

To get data passed from a form in Express and Node.js, we use the body-parser module.

For instance, we write

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

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

app.post("/game", (req, res) => {
  res.render("template", { name: req.body.name });
});

to call app.use to use the middleware returned by bodyParser.urlencoded to make our app parse form data request data.

Then we get the request body data from req.body as an object in the post /game route handler.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *