Getting Started with Express

https://goo.gl/m4gM1v

Express

  • What ?
  • Why?
  • How?

What?

Fast, unopinionated, minimalist web framework for Node js

Why?

  • lightweight framework === fast
  • Declarative Routing
  • Basic middleware pattern
  • Large ecosystem (plugin for nearly every thing)
  • incubated by node foundation in 2016

How?

  • installing
  • Setup the Server
  • Routing
  • middlewares
  • Respone
  • Request
  • template engines
  • MVC Demo Project Structure

Installing

mkdir demoapp
cd demoapp
npm init -y
npm install express --save

installing node https://nodejs.org

installing express

Setup express Server

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

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

app.listen(3000, () => console.log('Demo app listening on port 3000!'))

Routing

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

How?

app[HTTP_METHOD](ROUTE_PATH, ROUTE_HANDLER)

app[HTTP_METHOD](ROUTE_PATH, (REQUEST, RESQPONSE,NEXT) => {
// logic
// finialize and send the response
 RESPONSE.send('Hello World!')
})

Routing

// GET method route
app.get('/', function (req, res) {
  res.send('GET request to the homepage')
})

// POST method route
app.post('/', function (req, res) {
  res.send('POST request to the homepage')
})

/** Express supports the following routing methods that correspond to HTTP methods:
get, post, put, head, delete, options, trace, copy, lock, mkcol,
 move, purge, unlock, report, mkactivity, checkout, merge, m-search,
 notify, subscribe, unsubscribe, patch and search.
*/

Route Methods

Routing

// matches root path
app.get('/',(req, res) =>  res.send('root'));
// matches /about 
app.get('/about',(req, res) =>  res.send('about'));
// matches /random.text 
app.get('/random.text',(req, res) =>  res.send('random.txt'));
// matches /acd and /abcd
app.get('/ab?cd',(req, res) =>  res.send('ab?cd'));
// matches /abcd, /abbcd, /abbbcd 
app.get('/ab+cd',(req, res) =>  res.send('ab+cd'));
// matches /abcd, /abxcd, /abRANDOMcd, /ab123cd
app.get('/ab*cd',(req, res) =>  res.send('ab*cd'));
// matches /abe /abcde
app.get('/ab(cd)?e',(req, res) =>  res.send('ab(cd)?e'));
//you can use regx
// matches  /butterfly and /dragonfly, but not /butterflyman, /dragonflyman
app.get(/.*fly$/,(req, res) =>  res.send('/.*fly$/'));

Route Paths

Routing

app.get('/users/:userId/books/:bookId', (req, res) => {
  res.send(req.params)
})

/*
Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
*/

Route Parameters

Routing

// single handler
app.get('/example/a', (req, res) => {
  res.send('Hello from A!')
})

// multiple handlers behave like middlewares
app.get('/example/b', (req, res, next) => {
  console.log('the response will be sent by the next function ...')
  next()
}, (req, res) => {
  res.send('Hello from B!')
})

Route Handlers

Routing

// array of callbacks

const cb0 = (req, res, next) => {
  console.log('CB0')
  next()
}

const cb1 = (req, res, next) => {
  console.log('CB1')
  next()
}

const cb2 = function (req, res) => {
  res.send('Hello from C!')
}

app.get('/example/c', [cb0, cb1, cb2])

Route Handlers

Routing

//combination
const cb0 = (req, res, next) => {
  console.log('CB0')
  next()
}

const cb1 = (req, res, next) => {
  console.log('CB1')
  next()
}

app.get('/example/d', [cb0, cb1], (req, res, next) => {
  console.log('the response will be sent by the next function ...')
  next()
},(req, res) => {
  res.send('Hello from D!')
})

Route Handlers

Routing

app.route('/book')
  .get((req, res) => {
    res.send('Get a random book')
  })
  .post((req, res) => {
    res.send('Add a book')
  })
  .put((req, res) => {
    res.send('Update the book')
  })

app.route()

Routing

const express = require('express')
const router = express.Router()

// middleware that is specific to this router
router.use((req, res, next) => {
  console.log('Time: ', Date.now())
  next()
})
// define the home page route
router.get('/', (req, res) => {
  res.send('Birds home page')
})
// define the about route
router.get('/about', (req, res) => {
  res.send('About birds')
})

module.exports = router

express.Router

const birds = require('./birds')
// ...
app.use('/birds', birds)

Middleware

router.use((req, res, next) =>{
  // do what you want then call next
    next();
});

Basic middleware

Middleware

// available in Express v4.16.0 onwards
// if you use old version install 'body-parser' package

// parses incoming requests with JSON payloads
// https://expressjs.com/en/4x/api.html#express.json 
app.use(express.json([options]));


// parses incoming requests with urlencoded payloads
// https://expressjs.com/en/4x/api.html#express.urlencoded
app.use(express.urlencoded([options]))

// serves static files
// https://expressjs.com/en/4x/api.html#express.static
app.use(express.static(root, [options]))

express builtin middlewares v4

Body Parser

Response

Request

req.body request body
req.query query string
req.params url params
req.files needs middleware "multer
req.cookies needs middleware "cookie-parser"
req.ip ip
req.hostname hostname
req.secure secure or not
req.protocol protocol

Templating engines

const fs = require('fs') // this engine requires the fs module
app.engine('ntl', (filePath, options, callback) => {
 // define the template engine
  fs.readFile(filePath, (err, content) => {
    if (err) return callback(err)
    // this is an extremely simple template engine
    const rendered = content.toString()
                    .replace('#title#', '<title>' + options.title + '</title>')
                    .replace('#message#', '<h1>' + options.message + '</h1>')
    return callback(null, rendered)
  })
})
 // specify the views directory
app.set('views', './views');
// register the template engine
app.set('view engine', 'ntl');
/* index.html
#title#
#message#
*/
app.get('/', (req, res) => {
  res.render('index', { title: 'Hey', message: 'Hello there!' })
})

Yor own template engine

Templating engines

// npm install ejs --save

app.set('views', './views');
app.set('view engine', 'ejs');

/*views/index.ejs
<h1><%= name; %></h1>
*/

app.get('/', (req, res) => {
    res.render('index',{name: "salama"});
});


// see http://ejs.co/

Popular Templating engines

Demo

Getting started with express

By Salama Ashoush

Getting started with express

  • 150