Express.js GET Request
GET and POST both are two common HTTP requests used for building REST API’s. GET requests are used to send only limited amount of data because data is sent into header while POST requests are used to send large amount of data because data is sent in the body.
Express.js facilitates you to handle GET and POST requests using the instance of express.
Express.js GET Method Example 1
Fetch data in JSON format:
Get method facilitates you to send only limited amount of data because data is sent in the header. It is not secure because data is visible in URL bar.
Let’s take an example to demonstrate GET method.
File: index.html
- <html>
- <body>
- <form action=“http://127.0.0.1:8081/process_get” method=“GET”>
- First Name: <input type=“text” name=“first_name”> <br>
- Last Name: <input type=“text” name=“last_name”>
- <input type=“submit” value=“Submit”>
- </form>
- </body>
- </html>
File: get_example1.js
- var express = require(‘express’);
- var app = express();
- app.use(express.static(‘public’));
- app.get(‘/index.html’, function (req, res) {
- res.sendFile( __dirname + “/” + “index.html” );
- })
- app.get(‘/process_get’, function (req, res) {
- response = {
- first_name:req.query.first_name,
- last_name:req.query.last_name
- };
- console.log(response);
- res.end(JSON.stringify(response));
- })
- var server = app.listen(8000, function () {
- var host = server.address().address
- var port = server.address().port
- console.log(“Example app listening at http://%s:%s”, host, port)
- })