Using Express

In notebook:
FrontEndMasters API design
Created at:
backend JavaScript libraries Express
Hello World Example
  var express = require('express');

var app = express();

// on GET request to the url
app.get('/todos', function(req, res) {


// on POST request to the same url'/todos', function(req, res) {


// start server on port 3000
A server with two routes.
"The ​req​ and ​res​ objects have a lot of power". You modify and mutate them through your app.

A more complicated example for a todo app:
  var todos = [];

app.get('/todos', function(req, res) {
  // send back a json response
});'/todos', function(req, res) {
  var todo = req.body.todo;

  // res.send converts to json as well
  // but req.json will convert things like null and undefined to json too although its not valid

// get the parameters from the route
app.get('/todos/:id', function(req, res) {
  var todo = _.find(todos, {id:});

It will even concert null or undefined to JSON.

Uses lodash to work with the todo collection.

Very simple but powerful.

You can define more than one function per request type: that's a middleware.

If you do the same on GET and POST you're not adhering to REST.


To inspect and modify incoming requests. It's just a function, like above a callback.
A middleware will inspect the ​req​ object, act on it (or not) than pass to the next middleware. Or it can even stop the flow and send back immediately.

Routing and middleware are the two most important features of Express. Express is only 1 page long code.

All middleware are available as third-party libs.
Express can serve very well static assets. Chunks, reading files in buffers, etc.