Getting started with Express

Initialize the project and install and save express to package.json

npm init -y
npm i -S express

Here’s the code for a very basic server up and running

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

app.get('/', function (req, res) {
  res.send('Bonjour la monde!')

const server = app.listen(3001, function () {`Server running at http://localhost:${server.address().port}`)

install nodemon and add npm scripts to package.json

npm i -D nodemon
"scripts": {
  "start": "node index.js",
  "dev": "nodemon index.js"



For every route, you need a path and a route handler function (callback function) for that path

  • Path could be a string ('home'), path pattern (*.json), regex, or an array.
  • Callback could be a middleware function, a series of middleware functions, and array of middleware functions or all of these combined.
app.get('/yo',  function (req, res) {

whenever someone visits /yo, they’ll get a HEYO! in response.

You can pass in multiple handlers, like so

// function verifyUser (req, res, next) { .. }

app.get('/:username', verifyUser, function (req, res) {
  let user = req.params.username
  rese.render('user', {
    user: user,
    address: user.location


Response res in our callback route handler is an object, it has it’s own methods, like .send(), .redirect(), .status() etc. The res object is an enhanced version of Node’s own response object and supports all built-in fields and methods.

// Some example responses

// send a very simple string response

// send an 404
res.status(404).send(`No username ${req.params.username} found`)

// redirect to a page

// download a resource
app.get('*.json', function (req, res) {
  // whenever someone goes to a path ending in .json, download the corresponding file
  // e.g. i go to /mojojojo.json, i download the file at /users/mojojojo.json`./users/${req.path}`)
  // You can optionally provide a second param as file name
  //'filePath', 'fileName')`/users/${req.path}`, 'virus.exe`) // buahahaa

// JSON, send data back as json, like an API server

Route parameters

The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.

app.get('/users/:userId/books/:bookId', function (req, res) {
Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }