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

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives