Skip to content

07 Express

Jagdeep Singh edited this page May 22, 2019 · 1 revision

Express.js

Any number of functions that are invoked by the the Express.js routing layer before your final request handler is made.

All middleware functions have an optional next parameter which is the function to run next (callback).

Request —> Route -> [CORS —> CSRF —> Auth] —> Main task —> Response

// Psuedo-Code

let express = require('express');
let app = express();
let port = process.env.PORT || 8080;

app.get('/', (req, res) => {
  // middleware
  cors.initialize();
  auth.verify();
  
  // final request handler
  function(req, res) {
    res.render('index');
  }
});

app.post('/upload', auth.isAuthenticated(), controller.upload);

Using the ExpressJS 4.0 Router

What is a Router?

Router is like a mini express application, it doesn't bring in views or settings, but provides us with routing APIs like .use, .get, .param, and .route.

Basic Routes express.Router()

// server.js

// get an instance of router
var router = express.Router();

// home page route (http://localhost:8080)
router.get('/', function(req, res) {
    res.send('im the home page!');  
});

// about page route (http://localhost:8080/about)
router.get('/about', function(req, res) {
    res.send('im the about page!'); 
});

// apply the routes to our application
app.use('/', router);

Benefits of express.Router()

  • can create multiple express.Router()
    • can have a Router for our basic routes, authenticated routes, and even API routes.
  • allows us to make our applications more modular and flexible than ever before by creating multiple instances of the Router and apply them accordingly.

Clone this wiki locally