Notes

Expressjs

What is ExpressJS, why it is needed, a brief comparison with other frameworks and code examples

Edit on GitHub

Node API
4 minutes
  • Node has a builtin http module, which allows us to create an HTTP server on a TCP connection
  • The issue with the builtin module is that it requires a lot of code and configuration to setup something basic, and can be difficult and overwhelming
  • You’re forced to learn about stuff (like Networking), but it is also error-prone
  • Express is literally just a routing library with middleware
  • It allows you to set up verbs with routes and then run the functions you tell it to run when those routes and verbs are hit by a request

Express

Fast, unopinionated, minimalist web framework for Node.js

  • Express is a framework that abstracts that difficulty away and makes the process easier. It sits on top of node and uses the http module to make building servers not so hard.

Express vs. Others

  • Other alternatives include koa, hapi and sails to name a few. Express is by far the most popular one
  • Express is a framework that sits on top of http and there are other frameworks that sit on top of Express (e.g. Kraken, Sails, LoopBack), so there’s a lot of abstraction. Express is a good common ground to start
  • A lot of the really good frameworks are built on top of Express. So if you start with Express, you’ll have a real solid foundation and good understanding of conventions used by frameworks built on top of Express

Express vs. Restify

  • Express is meant to be a web server (you can have a website serving static assets as well as an API). Restify is only aimed at building a RESTful API
  • Express is very well maintained, better than maintained than Restify
  • Restify is a good one as far as API design is concerned in general

Using Express

Here’s how the code looks for a basic server in Express. With three lines of code you can have a server with two routes

 1// setup a server with Express
 2const express = require('express')
 3const app = express()
 4
 5// on GET request to the URL
 6app.get('/todos', (request, response) => {
 7	// for any GET requests to /todos, run this code
 8})
 9
10// on POST request to the same URL 
11app.post('/todos', (request, response) => {
12	// for any POST requests to /todos, run this code
13})
14
15// start server on port 3000
16app.listen(3000, () => {
17	console.log('Example app listening on port 3000!')
18})

Here’s how it would’ve looked with Node’s http module

 1// setup a server with Node's builtin http module
 2const http = require('http')  
 3const port = 3000
 4
 5const requestHandler = (request, response) => {  
 6  console.log(request.url)
 7  response.end('Hello Node.js Server!')
 8}
 9
10const server = http.createServer(requestHandler)
11
12server.listen(port, (err) => {  
13  if (err) {
14    return console.log('something bad happened', err)
15  }
16
17  console.log(`server is listening on ${port}`)
18})

Request and Response objects

  • req and res are short for request and response. They’re just objects in teh callback that we have access to, and the callback that gives us so much flexibility and so much power
  • On the request we have all the information about what is trying to access our server
  • The response gives us all types of ways to respond back to the client
  • Most of any API is modifying and manipulating these request and response objects to send back appropriate responses for appropriate requests

Here’s an example TODOs API

 1let todos = [
 2  'Finish this course',
 3  'Make some coffee',
 4  'Feed the fish',
 5  'Wash the car'
 6]
 7
 8app.get('/', (req, res) => {
 9  res.send('Hello there, this is my todos app. Go to /todos to get all todo items')
10})
11
12app.get('/todos', (request, response) => {
13  // send back a JSON response
14  response.json(todos)
15})
16
17app.post('/todos', (req, res) => {
18  let todo = req.body.todo
19
20  todos.push(todos)
21  // res.send() will convert to JSON as well
22  // but req.json will convert things like null and undefined to JSON too although it's not valid
23  res.send(todo)
24})
25
26// get the response from the route
27app.get('/todos/:id', (req, res) => {
28  let todo = _.find(todos, {id: req.params.id})
29
30  res.json(todo)
31})
res.json() vs. res.send()
  • res.json() will convert to JSON everything, including null and undefined, which are not exactly valid values..