Express.js

Jump to...

Installing Express

{
 "name": "my-project-folder-name",
 "version": "1.0.0",
 "description": "",
 "main": "index.js",
 "scripts": {
   "test": "echo \"Error: no test specified\" && exit 1"
 },
 "keywords": [],
 "author": "",
 "license": "ISC",
 "dependencies": {
   "express": "^4.17.1"
 }
}

Creating an Express Application

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

Routing

Route Methods

Route Paths

List of root paths

Route Parameters

Route Handlers

Middleware

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

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

app.listen(3000)

Listening for HTTP Connections

Configurable Middleware

module.exports = function (options) {
  return function (req, res, next) {
    // Implement the middleware function based on the options object
    next()
  }
}

The middleware can now be used as shown below.

var mw = require('./my-middleware.js')

app.use(mw({ option1: '1', option2: '2' }))

An Express Application can use the following types of middleware:

Function Action Arguments
express.static(root, [options]) serves status assets such as HTML files, images, and so on. root: specifies the root directory options: options object
express.json([options]) parses incoming requests with JSON payloads options: options object
express.urlencoded([options]) parses incoming requests with URL-encoded payloads options: options object

Sessions

Installing Express sessions

 npm install express-session

Adding express-session middleware to the app module.

 const express = require('express');
const session = require('express-session');

const app = express();

app.set('view engine', 'pug');
app.use(session({
  secret: 'a5d63fc5-17a5-459c-b3ba-6d81792158fc',
  resave: false,
  saveUninitialized: false,
}));

Session Store

Drawbacks

Express Methods

Request Application Response Router Middleware
req.accepts() app.delete() res.append() () router.all() bodyParser()
req.acceptsCharsets() app.disable() res.attachment() router.METHOD() compress()
req.acceptsEncodings() app.enable() res.cookie() router.param() cookieParser()
req.acceptsLanguages() app.engine() res.clearCookie() router.route() cookieSession()
req.get() app.get() res.download() router.use() csrf()
req.is() app.listen() res.end() errorHandler()
req.param() app.method() res.format() methodOverride()
req.range() app.param() res.get() morgan()
app.path() res.json() responseTime()
app.post() res.links() favicon()
app.put() res.location() directory()
app.render() res.redirect() serveStatic()
app.route() res.render() timeout()
app.set() res.send() vhost()
app.use() res.sendFile() session()
res.sendStatus()
res.set()
res.status()
res.type()
res.vary()

Express Properties

Request Response Application
req.app res.app app.locals
req.baseUrl res.headersSent app.mountpath
req.body res.locals
req.cookies
req.fresh
req.hostname
req.ip
req.ips
req.method
req.originalUrl
req.params
req.path
req.protocol
req.query
req.route
req.secure
req.signedCookies
req.stale
req.subdomains
req.xhr

Forms

<form action="/team_name_url/" method="post">
    <label for="team_name">Enter name: </label>
    <input id="team_name" type="text" name="name_field" value="Default name for team.">
    <input type="submit" value="OK">
</form>

Form Handling

Process flowchart for processing form requests
  1. Display the default form the first time it is requested by the user.
  1. Receive data submitted by the user, usually in an HTTP POST request.
  2. Validate and sanitize the data.
  3. If any data is invalid, re-display the form—this time with any user populated values and error messages for the problem fields.
  4. If all data is valid, perform required actions (e.g. save the data in the database, send a notification email, return the result of a search, upload a file, etc.)
  5. Once all actions are complete, redirect the user to another page.

Validation and Sanitazion

Routes

Bootstrap Form Control

Error Handling

The default error handler

Template Inheritance

Block append / prepend