Express

Junghoo Cho

cho@cs.ucla.edu

Express

Express Demo

// -------- app.js ---------
let express = require('express');
let app = express();

app.get('/', (req, res, next) => {
    res.send('Hello World!');
});
app.get('/john', (req, res, next) => {
    res.send('Hello, John!');
});
app.listen(3000);

$ mkdir demo; cd demo              // create demo directory        
$ npm init -y; npm install express // install express
$ node app.js                      // run app.js

URL Routing

Request Handler

Request Handling Chain

Generating Response

Generating Body (1)

  1. Raw string: res.send(body)
  2. Static file: res.sendFile(absolute_path)
  3. JSON: res.json(object)

Generating Body (2)

  1. Generate from Template: res.render(template-file, template-data)

EJS Template Engine

EJS Example (1)

<!-- index.ejs --->
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body>
<ul>
<% for (let post of posts) { %>
    <li><%= post.title %></li>
<% } %>
</ul>
</body>

EJS Example (2)

// ----  app.js ------
let express = require('express');
let app = express();
app.set('view engine', 'ejs'); // template engine to use
app.set('views', '.')          // view template directory

app.get('/', (req, res, next) => {
    res.render("index",
        { title: "Hello",
          posts: [{title: "Title 1"}, {title: "Title 2"}]
        }
    );
});
app.listen(3000);

Advanced URL Routing (1)

Advanced URL Routing (2)

Modular Middleware

express.Router() Example

// create a router
let birds = express.Router();
birds.get('/sparrow', (req, res, next) => res.send("Sparrow"));
birds.get('/dove', (req, res, next) => res.send("Dove"));

// mount the router at a prefix
app.use('/birds', birds);

Standard Middleware

Middleware Example

let express = require('express');
let path = require('path');
let bodyParser = require('body-parser');
let app = express();

app.use('/json', bodyParser.json());
app.use('/www', express.static(path.join(__dirname, 'public')));

app.listen(3000);

Error Handling

Error Handler

Express Application Generator

MVC in Express

What We Learned