Express

Express.js, or simply Express, is a back end web application framework for Node.js. It is designed for building web applications and APIs.

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

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

npm install express body-parser morgan

  • express - a framework for building servers
  • body-parser - a middleware that parses incoming requests
  • morgan = a middleware for logging incoming requests

With everything installed, we'll create a simple API for a todo app using express.

import express from 'express'
import morgan from 'morgan'
import bp from 'body-parser'

const { urlencoded, json } = bp

const db = {
  todos: [],
}

const app = express()

app.use(urlencoded({ extended: true }))
app.use(json())
app.use(morgan('dev'))

app.get('/todo', (req, res) => {
  res.json({ data: db.todos })
})

app.post('/todo', (req, res) => {
  const newTodo = { complete: false, id: Date.now(), text: req.body.text }
  db.todos.push(newTodo)

  res.json({ data: newTodo })
})

app.listen(8000, () => {
  console.log('Server on http://localhost:8000')
})

Compared to the native http module, express feels like cheating.

Our todo API has two routes:

  • GET /todo - get all todos
  • POST /todo - create a new todo

Children
  1. Middleware

Backlinks