Handle GET and POST Request in Express
- remove_red_eye337139 Views
- event20 Oct 2020
- access_time7 min read
GET and POST is two common HTTP Requests used for building REST APIs. Both of these calls are meant for some special purpose.
As per the documentation GET requests are meant to fetch data from specified resource and POST requests are meant to submit data to a specified resource.
Express framework provides router() method to create HTTP endpoints. Let’s checkout how to handle GET and POST request using Express.
If you are new to Node then you should checkout our detailed Node course. Its FREE!
GET request:
Handling GET request in Express is pretty straightforward. You have to create instance of express and router. Here is small snippet to achieve the same.
const router = express.Router();
const app = express();
router.get('/handle',(request,response) => {
//code to perform particular action.
//To access GET variable use req.query() and req.params() methods.
});
// add router in the Express app.
app.use("/", router);
GET requests can be cached and remains in the browser history. This is why the GET method is not recommended to use for sensitive data (passwords, ATM pins, etc). You should GET requests to retrieve data from the server only.
Let’s check out the POST method.
POST Request:
Express requires an additional middleware module to extract incoming data of a POST request. This middleware is called as ‘body-parser’. We need to install it and configure it with Express instance.
You can install body-parser using the following command.
You need to import this package in your project and tell Express to use this as middleware. Refer this code for a reference.
const bodyParser = require("body-parser");
const router = express.Router();
const app = express();
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
router.post('/handle',(request,response) => {
//code to perform particular action.
//To access POST variable use req.body()methods.
console.log(request.body);
});
// add router in the Express app.
app.use("/", router);
In this way, you can handle the GET and POST request in the Express framework.
Demo App : Login System
To demonstrate this I am going to code one simple log-in System which will use GET request to serve HTML page to client and POST request from the client to send user name and password to Server.
Let’s create a new Node.js project.
Let’s install the dependencies.
Next, let’s create an Express web server.
const bodyParser = require("body-parser");
const router = express.Router();
const app = express();
app.listen(3000,() => {
console.log("Started on PORT 3000");
})
Run Server using
We will use Express Router to handle routes of app. So when user request the app from web browser, we will serve the HTML file.
res.sendfile("index.html");
});
When user click on log-in button on HTML page we will POST request to Server and get the response.
var user_name = req.body.user;
var password = req.body.password;
console.log("User name = "+user_name+", password is "+password);
res.end("yes");
});
Here is complete Server code.
const bodyParser = require("body-parser");
const router = express.Router();
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
router.get('/',(req, res) => {
res.sendfile("index.html");
});
router.post('/login',(req, res) => {
var user_name = req.body.user;
var password = req.body.password;
console.log("User name = "+user_name+", password is "+password);
res.end("yes");
});
app.listen(3000,() => {
console.log("Started on PORT 3000");
})
On front-end we will create simple HTML file and call the POST request using Ajax. Here is a code of HTML page.
<head>
<title>Simple login</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
var user,pass;
$("#submit").click(function(){
user=$("#user").val();
pass=$("#password").val();
$.post("http://localhost:3000/login",{user: user,password: pass}, function(data){
if(data === 'yes') {
alert("login success");
}
});
});
});
</script>
</head>
<body>
<h1>Hello people !</h1>
<input type="TEXT" id="user" size="40"><br>
<input type="password" id="password" size="40"><br>
<input type="button" id="submit" value="Submit">
</body>
</html>
Here is a video demonstration of the app.