Saturday, June 6, 2020

Expressjs get method

ExpressJS GET method

GET and POST is HTTP methods, used to transfer the HTTP data from the client to the server. The GET method can send a limited amount of data because the data is send appended with the URL in name or value pair.


The app.get() routes(read ExpressJS Routing)  HTTP requests to the provided path with the provided callback functions. The syntax of this method is,

app.get(path, callback [, callback ...])

Here, The path represents the path for which the middleware function is called,  It can be,

  • A string representing a path,
  • A pattern representing possible paths
  • A regular expression pattern to match paths
  • An array of combinations of any of the above.
The default value of the root path is '/'.

A Callback function can be,

  • A middleware function.
  • A series of middleware functions (separated by commas).
  • An array of middleware functions.
  • A combination of all of the above.
The default value of the Callback parameter is None.

There can be more than one callback function that acts just like middleware, besides that these callbacks may invoke next('route') to bypass the remaining route callback(s). This technique can be applied to impose pre-conditions on a route, and then pass control of execution to following routes if there is no reason to continue with the current route.

app.get() Example

Write index.html as follows,

<form action="http://localhost:3000/get_demo" method="GET">  
<input type="text" name="fname" placeholder="First name">  <br>  
<input type="text" name="lname" placeholder="Last name"> <br> 
<input type="submit" value="Submit">  

Write get_demo.js as follows,

var express = require('express');  
var app = express();  
app.get('/index.html', function (req, res) {  
   res.sendFile( __dirname + "/" + "index.html" );  
app.get('/get_demo', function (req, res) {  
fullname = {  
var server = app.listen(3000, function () {  
  var host = server.address().address  
  var port = server.address().port  
  console.log("listening at http://%s:%s", host, port)  

The output would appear as,