ExpressJS: Node.js Web Application Framework

Posted By : Ankit Uniyal | 30-Sep-2018

The goal of this blog is to discuss what is ExpressJS and how to set up express server, define Middleware and how ExpressJS is useful with the NodeJs application.

 

ExpressJS is basically a fast, unopinionated, minimalist web framework for Node.js. It is a layer built on top of Node.js that helps manage a server and our routes.

 

Why use Express?

 

Because Express a server side framework which works on top of Node as it works for Ultra-Fast Input and Output. Node.js is built asynchronous and single threaded meaning when a request can be made simultaneously without occurring a bottleneck as that will slow down the processing.


There are bust API's that ships withExpressallows us to easily configure routes to send and receive requests from a frontend and connect to a database.

 

Installation of ExpressJS: 

You can install express globally using npm:

npm install -g express 

 

Below is the basic code snippet to use express in your project: 

 

var express = require('express');
var app = express()

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

 

How to set up Express Server: 

 

1.Create a new folder let's say project and then navigaet to the folder in your terminal and then type npm init to create package.json file in your project location.

2.Create an app.js file and then install express package using below command on your terminal after you navigate to your project location.

npm install --save express

You will see the express dependency can be seen on package.json file.

You can also install nodemon globally:

npm install -g nodemon

 

Here is the complete app.js file to set up your express server:

 

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//app.use('/', routes);
app.use('/users', users);

app.get('/', function(req, res) {
  res.render('index', {title: 'Welcome to express'});
});

app.get('/search', function(req, res) {
    var query = req.query.id;
    res.send('id: ' + query);
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;           
        

 

What is Middleware:

Middleware is any number of functions that can be invoked by the ExpressJS routing layer before you final request handler is made.

So essentially we're saying that honored to find a route do something fist then pass it along to the next function.

 

app.get('/myroute', function(res, req, next) {
    //Do something
    next();
}, function(req, res) {
    //Do something else
}
});          
        

 

Each time we use the request and response objects of the HTTP cycle in order to alter and or pass to the next whatever it is that we're handling.

So in this example before sending someone to the route that they request we would deal with any callers or S S RF issues that may arise.


We check to see if the user with was authorized for that route and if it is all good then we would send them to where they want to go.


And this is what a pseudo code example would look like for the previous image.

 

app.get('/',
    //Do something
    cors.initialize(),

    //Do Something Else....
    auth.verify(),

    //Send the Response
    function(req, res) {
        res.render(index);
    }
);         
        

 

Hope that it helps out.

Thanks.

Request for Proposal

Recaptcha is required.

Sending message..