Express
Express is a mini and flexible Node.js web application framework that gives a strong set of features to develop web and mobile applications. It facilitates the fast development of Node based Web applications.
Following are some of the core features of Express framework-
Allow to set up middlewares to rspond to HTTP Requests.
Defines a routing table which is used to perform different actions based on HTTP method and URL.
Allow to dynamically render HTML pages based on passing arguments to templates.
First of all install the Express framework globally using NPM so that it can be used to create a web application using node terminal.
$ npm install express --save
This code installs the node modules directory and creates a directory express inside the node modules. There some other important modules to be install with express.
Body parser- this handles JSON, Raw, Text and URL encoded form data.
$ npm install body-parser --save
Cookie-parser - parse cookie header and populate req.cookies with an object keyed by the cookie names.
$ npm install cookie-parser --save
multer- Its a node.js middleware for handling mulitipart/form-data.
$ npm install multer --save
Hello world Example
var express = require('express');
var app = express();
app.get('/', function (req, res){
res.send('Hello World');
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%:%s", host, port)
})
port
A port number on which the server should accept incoming requests.
host
Name of the domain. You need to set it when you deploy your apps to the cloud.
backlog
The maximum number of queued pending connections. The default is 511.
callback
An asynchronous function that is called when the server starts listening for requests.
Router
App.method
This METHOD can be applied to any one of the HTTP verbs – get, set, put, delete. An alternate method also exists, which executes independent of the request type.
Path is the route at which the request will run.
Handler is a callback function that executes when a matching request type is found on the relevant route.
var express = require('express');
var app = express();
app.get('/hello', function (req, res){
res.send('Hello World');
});
app.listen(3000);
HTTP Methods
GET
The GET method requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect.
POST
The POST method requests that the server accept the data enclosed in the request as a new object/entity of the resource identified by the URI.
PUT
The PUT method requests that the server accept the data enclosed in the request as a modification to existing object identified by the URI. If it does not exist then the PUT method should create one.
DELETE
The DELETE method requests that the server delete the specified resource.


No comments