Express js GET Request

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

  1. <html>
  2. <body>
  3. <form action=“http://127.0.0.1:8081/process_get” method=“GET”>
  4. First Name: <input type=“text” name=“first_name”>  <br>
  5. Last Name: <input type=“text” name=“last_name”>
  6. <input type=“submit” value=“Submit”>
  7. </form>
  8. </body>
  9. </html>

File: get_example1.js

  1. var express = require(‘express’);
  2. var app = express();
  3. app.use(express.static(‘public’));
  4. app.get(‘/index.html’, function (req, res) {
  5.    res.sendFile( __dirname + “/” + “index.html” );
  6. })
  7. app.get(‘/process_get’, function (req, res) {
  8. response = {
  9.        first_name:req.query.first_name,
  10.        last_name:req.query.last_name
  11.    };
  12.    console.log(response);
  13.    res.end(JSON.stringify(response));
  14. })
  15. var server = app.listen(8000, function () {
  16.   var host = server.address().address
  17.   var port = server.address().port
  18.   console.log(“Example app listening at http://%s:%s”, host, port)
  19. })

About Author

Leave a Reply

Your email address will not be published. Required fields are marked *

PAGE TOP
error

Enjoy this blog? Please spread the word :)

RSS
Follow by Email