Monday, 18 September 2017

ExpressJS - a basic demo

We have set up the development [click here], now it is time to start developing our first app using Express. Create a new file called index.js and type the following in it.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
var express = require('express');
var app = express();

app.get('/', function(req, res){
res.send("Hello world!");
});

var server = app.listen(5000, function () {  
var host = server.address().address;  
var port = server.address().port;  
console.log('App listening at http://%s:%s', host, port);  
});  

Save the file, go to your terminal and type the following.

nodemon index.js

This will start the server. To test this app, open your browser and go to http://localhost:5000 and a message will be displayed as in the following screenshot.

How the App Works?
The first line imports Express in our file, we have access to it through the variable Express. We use it to create an application and assign it to var app.

app.get(route, callback)
This function tells what to do when a get request at the given route is called. The callback function has 2 parameters, request(req) and response(res). The request object(req) represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, etc. Similarly, the response object represents the HTTP response that the Express app sends when it receives an HTTP request.

res.send()
This function takes an object as input and it sends this to the requesting client. Here we are sending the string "Hello World!".

app.listen(port, [host], [backlog], [callback]])
This function binds and listens for connections on the specified host and port. Port is the only required parameter here.

S.No.Argument & Description
1
port
A port number on which the server should accept incoming requests.
2
host
Name of the domain. You need to set it when you deploy your apps to the cloud.
3
backlog
The maximum number of queued pending connections. The default is 511.
4
callback
An asynchronous function that is called when the server starts listening for requests.

0 comments:

Post a Comment

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)