Node JS Tutorial - Handling POST Requests

In this tutorial, we will learn about handling POST requests in Node.js.

POST and GET are two common HTTP requests used for building REST APIs. Each has a specific purpose: GET requests are used to fetch data from a specified resource, while POST requests are used to submit data to a specified resource.

In Express version 4 and above, an extra middleware layer is required to handle POST requests. This middleware is called 'bodyParser'. Let's install it.

Open the command prompt and run the following command:


npm install body-parser

Next, we need to import the bodyParser package in our project and tell Express to use it as middleware. Open the index.js file and import the package:


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

Now, configure Express to use bodyParser as middleware:


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

With bodyParser set up, we can now use the app.post Express router to handle POST requests. Let's create a route:


app.get('/login',function(req,res){
res.render('login');
});

Create a view by going to the views directory and creating a new file called login.ejs. Open login.ejs and add the following code:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<form method="POST" action="/post">
<div class="form-group">
<label for="email">Email </label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</body>
</html>

Create the POST route by going to the index.js file and adding the following code:


app.post('/post',function(request,response){
var email=request.body.email;
var password=request.body.password;
res.send('Email'+email + " Password: "+password);
});

Now, let's run the application. Go to the command prompt and run the index.js file:


node index.js

The application is now running. Go to the browser and navigate to the URL /login. Fill in the email and password fields and click the submit button. You should see the submitted email and password displayed.

This is how you can handle POST requests in Node.js.