Express Is Adorbs

Express is adorable. It’s the tiniest, cutest little web framework.

Besides adorable, Express is a lightweight web framework for Node.js. It addresses a few basic needs of Node applications.

Node Express
need to implement whole HTTP server convenience methods for easy-to-start server
need a router to map requests to request handlers routes requests to designated handler based on HTTP verb + path
need to actually handle requests callbacks handle requests!

Hello world

A “hello world” Express server is very simple. Besides the standard package.json + node_modules (libraries) that come with a new Node project, here’s all it took:

$ npm install express --save

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// app.js

var express = require('express')
var app = express() // creates an Express application

// `app` has methods like `.get` for routing HTTP requests
app.get('/', (req, res) => {
  var host = req.get('host') // `req` is an object representing the HTTP request
  res.send("try visiting " + host + "/helloworld instead")
})

app.get('/helloworld', (req, res) => {
  // `res` is an object representing the HTTP response
  res.send("hello world")
})

// `.listen` is a convenience function that does some stuff to start an HTTP server
app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

That’s all there is to it. Run node app.js on the command line, open up localhost:3000 in a browser, and you’re all set.

Bonus fun

res and req (the arguments passed into each callback) are pretty powerful objects. Built on Node’s own response and request objects, these objects come with helpful methods to read the request or alter the response body.

For example, you can have the response send back JSON instead of a regular String:

1
2
3
app.get('/json', (req, res) => {
  res.json({ msg: 'this is json' });
})

I really like the simple route layout that Express encourages. Each route is a simple combination of HTTP verb + path. (A REST best practice, incidentally: keep the URL the same but vary the verb.)

In the following example, when we load and submit an HTML form, we hit two different /upload endpoints.

1
2
3
4
5
6
7
8
9
10
11
12
13
app.get('/upload', (req, res) => {
  const form = `
    <form action='/upload' method='post'>
      Submit this form
      <input type='submit' />
    </form>
  `
  res.send(form)
})

app.post('/upload', (req, res) => {
  res.send('hello! upload complete')
})

Hello, World (of Express)!