📖
Maissen's Grimoire
  • Maissen's Grimoire
  • Html and css grimoire
    • HTML5 Periodical Table
    • HTML Cheat Sheet
    • CSS Cheatsheets
  • Javascript Grimoire
    • JavaScript Cheat Sheet
      • Javascript Array in depth
      • Tagged Template Literals
      • Guard Clauses - The Best Way To Write Complex Conditional Logic
      • JavaScript Optional Chaining
      • JavaScript Null Coalesce
      • What Are Magic Numbers And Why Are They Bad
      • ES6/ECMAScript2015 Cheatsheet
      • First-class and Higher Order Functions: Effective Functional JavaScript
    • Useful JavaScript Tips, Tricks and Best Practices
    • Bits of code
    • Useful JavaScript libraries
      • Components
      • Animation
      • Maps
      • Helpers
      • Presentations
      • Charts
      • Games
      • Audio
      • Images
      • Video
    • Js the right way
  • Angular Grimoire
    • Angular doc
    • Getting Started
    • Angular clean architecture
    • Angular Cheat Sheet
    • TypeScript Cheat Sheet
    • My Favorite Tips and Tricks in Angular
    • NgRx: tips & tricks
    • Bits of code
      • Execute Multiple HTTP Requests in Angular
      • Authentification
        • Angular 8 JWT Authentication with HttpInterceptor and Router
      • Integrations
        • Spring Boot
          • Rest Example
            • Angular,Spring Boot,Spring Data and Rest Example(CRUD)
          • Authentification
            • Angular, Spring Boot: JWT Authentication with Spring Security example
            • Angular Spring Boot Security Oauth2
              • Spring Boot OAUTH2 Role-Based Authorization
              • Spring Boot Security Google Oauth
              • Spring Security OAuth2 User Registration
    • Most used dependency
  • Node Grimoire
    • Express.js 4 Cheatsheet
    • Useful Dependencies
    • How To Use And Write Express Middleware
    • Node.js with SQL databases
      • Node.js Token Based Authentication & Authorization example
      • Node.js Rest APIs example with Express, Sequelize & MySQL
      • Node.js Express & PostgreSQL: CRUD Rest APIs example with Sequelize
      • Sequelize
        • Sequelize Many-to-Many Association example – Node.js & MySQL
        • Sequelize One-to-Many Association example with Node.js & MySQL
    • Node.js with NOSQL databases
      • Node.js + MongoDB: User Authentication & Authorization with JWT
      • Node.js, Express & MongoDb: Build a CRUD Rest Api example
      • MongoDB One-to-One relationship tutorial with Mongoose example
      • MongoDB One-to-Many Relationship tutorial with Mongoose examples
      • MongoDB Many-to-Many Relationship with Mongoose examples
  • Upload files
    • How to upload multiple files in Node.js
    • Upload & resize multiple images in Node.js using Express, Multer, Sharp
    • Upload/store images in MySQL using Node.js, Express & Multer
    • How to upload/store images in MongoDB using Node.js, Express & Multer
  • React Grimoire
    • React Doc
    • React Grimoire
    • React Cheat Sheet
  • spring boot Grimoire
    • Getting started
    • Spring Boot, Spring Data JPA – Rest CRUD API example
    • Spring Boot Token based Authentication with Spring Security & JWT
  • Mongo Grimoire
    • MongoDb-Mongoose Cheat Sheet
  • Development tools
    • Design Patterns
  • maissen_grimoire
Powered by GitBook
On this page
  • Installation
  • Generator
  • Basics
  • HTTP Verbs and Routes
  • Request
  • Request Header Shortcuts
  • Response
  • Handlers Signatures
  • Stylus and Jade
  • Body
  • Static
  • Connect Middleware
  • Other Popular Middleware

Was this helpful?

  1. Node Grimoire

Express.js 4 Cheatsheet

Installation

  • $ sudo npm install express: install the latest Express.js locally

  • $ sudo npm install express@4.2.0 --save: install Express.js v4.2.0 locally and save to package.json

  • $ sudo npm install -g express-generator@4.0.0: install Express.js command-line generator v4.0.0

Generator

Usage: $ express [options] [dir]

Options:

  • -h: print the usage information

  • -V: print the express-generator version number

  • -e: add ejs engine support, defaults to jade if omitted

  • -H: add hogan.js engine support

  • -c <library> add CSS support for (less|stylus|compass), defaults to plain CSS if omitted

  • -f: generate into a non-empty directory

Basics

  • var express = require('express'): include the module

  • var app = express(): create an instance

  • app.listen(portNumber, callback): start the Express.js server

  • http.createServer(app).listen(portNumber, callback): start the Express.js server

  • app.set(key, value): set a property value by the key

  • app.get(key): get a property value by the key

HTTP Verbs and Routes

  • app.get(urlPattern, requestHandler[, requestHandler2, ...])

  • app.post(urlPattern, requestHandler[, requestHandler2, ...])

  • app.put(urlPattern, requestHandler[, requestHandler2, ...])

  • app.delete(urlPattern, requestHandler[, requestHandler2, ...])

  • app.all(urlPattern, requestHandler[, requestHandler2, ...])

  • app.param([name,] callback):

  • app.use([urlPattern,] requestHandler[, requestHandler2, ...])

Request

  • request.params: parameters middlware

  • request.param: extract one parameter

  • request.query: extract query string parameter

  • request.route: return route string

  • request.cookies: cookies, requires cookie-parser

  • request.signedCookies: signed cookies, requires cookie-parser

  • request.body: payload, requires body-parser

Request Header Shortcuts

  • request.get(headerKey): value for the header key

  • request.accepts(type): checks if the type is accepted

  • request.acceptsLanguage(language): checks language

  • request.acceptsCharset(charset): checks charset

  • request.is(type): checks the type

  • request.ip: IP address

  • request.ips: IP addresses (with trust-proxy on)

  • request.path: URL path

  • request.host: host without port number

  • request.fresh: checks freshness

  • request.stale: checks staleness

  • request.xhr: true for AJAX-y requests

  • request.protocol: returns HTTP protocol

  • request.secure: checks if protocol is https

  • request.subdomains: array of subdomains

  • request.originalUrl: original URL

Response

  • response.redirect(status, url): redirect request

  • response.send(status, data): send response

  • response.json(status, data): send JSON and force proper headers

  • response.sendfile(path, options, callback): send a file

  • response.render(templateName, locals, callback): render a template

  • response.locals: pass data to template

Handlers Signatures

  • function(request, response, next) {}: request handler signature

  • function(error, request, response, next) {}: error handler signature

Stylus and Jade

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

app.use(require('stylus').middleware(path.join(__dirname, 'public')))

Body

var bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
    extended: true
}))

Static

app.use(express.static(path.join(__dirname, 'public')))

Connect Middleware

$ sudo npm install <package_name> --save

Other Popular Middleware

PreviousMost used dependencyNextUseful Dependencies

Last updated 1 year ago

Was this helpful?

request payload

gzip

Cookies

Session via Cookies store

CSRF

error handler

session via in-memory or other store

HTTP method override

server logs

favicon

static content

and : analogous to cookie-parser

,

: analogous to query

, analogous to staticCache

: validation

: LESS CSS

: authentication library

: security headers

: CORS

body-parser
compression
connect-timeout
cookie-parser
cookie-session
csurf
errorhandler
express-session
method-override
morgan
response-time
serve-favicon
serve-index
serve-static
vhost
cookies
keygrip
raw-body
connect-multiparty
connect-busboy
qs
st
connect-static
express-validator
less
passport
helmet
cors
connect-redis