Notes On Express JS

Table of Contents

Overview

Fast, unopinionated, minimalist web framework for node.

Synopsis

Basic node js hello world app:

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

With JVM you have HttpServer and HttpHandler. In addition the servlet API provides better modular support for individual get, post methods and such. Similarly, if you want to abstract away the httpServer details and directly deal with get, post handlers, you want use lightweight framework like express js.

Hello world express node application:

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

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

app.listen(3000)

FAQ

app.get vs app.use vs app.all

  • app.use() handles all methods for one end point.
  • app.get(), app.post() etc handle one method at a time.
  • You can also use app.use() to bind middleware (like interceptor) to do some filter operations and let it pass forward for further processing.

For simple, static routes:

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

vs.

app.use('/', function (req, res, next) {
  if (req.method !== 'GET' || req.url !== '/')
    return next();

  // ...
});

In addition, note the following :

app.use( "/book" , middleware);
// will match /book
// will match /book/author
// will match /book/subject
// next() call will invoke next middleware or handler.

app.all( "/book" , handler);
// will match /book
// won't match /book/author   
// won't match /book/subject    

app.all( "/book/*" , handler);
// won't match /book        
// will match /book/author
// will match /book/author

In addition, app.use() can be used as below:

bodyParser = require('body-parser');

// support parsing of application/json type post data
// It results in req.body being a json object if user had submitted
// application/json data in the body.
app.use(bodyParser.json());

//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));

The body-parser module was integrated inside express module in earlier versions. Now it is a separate NPM module.

app.get parameters support

app.get('/item/:id', function (req, res) {
 let id = req.params.id;
 // ...
});