Express.js GET Method

As we know GET and POST methods are used in HTTP Requests for creating API’s. Let see how to utilize the same in Express.

Lets create index.html with below code.
<html>
<body>  
<form action="http://127.0.0.1:8080/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> 

Here we have a form with 2 input fields and a submit button. On form submit data is submitted to process_get

Lets create a file server.js with below code.
var express = require('express');  
var app = express();  
  
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(8080, function () {  
  
  var host = server.address().address  
  var port = server.address().port  
  console.log("Example app listening at http://%s:%s", host, port)  
  
}) 

From the above code we can see, HTTP server will be started and listen to port 8080.

Below routing is defined

1. /index.html – when a request comes for /index.html then the index.html is rendered.

We can use the URL below to open it in the browser.

http://localhost:8080/index.html 
Below screenshot shows the output on the browser.

express-server.js

2. /process_get – when a request comes for process_get, it will form the response with the params in HTTP header and display it on screen as json.

Below screenshot shows the input entered in index.html. (before submit).

express-process-js

Now lets see the Json post form submit

express-json

Below screenshot shows the Json output on the browser

express-json-post.jpg

We can also use res.send, which we used in our sample application.

Subscribe Now