Instagram
youtube
Facebook
Twitter

ExpressJS- GET Request

Express.js GET Request

  • GET is a common HTTP request used for building REST API.
  • It is used to fetch data.
  • Fetch data using GET Method in JSON format and paragraph format.

Example

  • Data in JSON format

In 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>  

In example.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)  
  
})
  • Data in Paragraph format

In index.html

<html>  
<body>  
<form action="http://127.0.0.1:8000/get_example2" method="GET">  
First Name: <input type="text" name="first_name"/>  <br/>  
Last Name: <input type="text" name="last_name"/><br/>  
<input type="submit" value="Submit"/>  
</form>  
</body>  
</html>  

In example2.js

var express = require('express');  
var app=express();  
app.get('/get_example2', function (req, res) {  
res.send('<p>Username: ' + req.query['first_name']+'</p><p>Lastname: '+req.query['last_name']+'</p>');  
})  
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)  
})