How to access the POST query parameters in Express
In this tutorial, we are going to learn about how to retrieve the POST query parameters using express which is sent by the HTML forms.
Getting started
First, we are creating a simple HTML form that contains two input fields (email, password) and we are sending that data to the express /login
route.
<form action="http://localhost:3000/login" method="post"> <div>
<label for="email">Email: </label>
<input type="email" id="email" name="email"></input> </div>
<div>
<label for="password">Password: </label>
<input type="password" id="password" name="password"></input> </div>
<button type="submit">Login</button>
</form>
Accessing Data
To access the data in express /login
route handler, first we need to enable the express.urlencoded()
middleware then we can access that data using req.body
object.
const express = require("express");
const app = express();
app.use(express.urlencoded()); // middleware
app.post("/login", (req, res) => {
const email = req.body.email; const password = req.body.password;
console.log(email, password);
});
app.listen(3000, () => console.log("Server is running!!"));
In the above code, we have used email
and password
properties on req.body
object to access the data because we defined the same names inside the input
field name
attributes.
Similarly, if you are sending a form data using HTTP clients for example Axios or Fetch API, you need to enable the express.json()
middleware and use req.body
object for accessing the data.
const express = require("express");
const app = express();
app.use(express.urlencoded());
app.use(express.json());