Skip to content

Express

all1124 edited this page Oct 18, 2019 · 5 revisions

Express

  • Express is a routing and middleware web framework
  • An Express application is essentially a series of middleware function calls
  • Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle
  • The next middleware function is commonly denoted by a variable named next
  • Middleware functions can perform the following tasks:
    • Execute any code
    • Make changes to the request and the response objects
    • End the request-response cycle
    • Call the next middleware function in the stack
  • Application-level middleware
    • app.use()
    • app.METHOD() functions
  • Router-level middleware
    • router.use()
    • router.METHOD() function
  • Error-handling middleware
    • You must provide four arguments to identify it as an error-handling middleware function
  • These functions are used to modify req and res objects for tasks like parsing request bodies, adding response headers, etc `var express = require('express'); var app = express();

        //Simple request time logger
        app.use(function(req, res, next){
        console.log("A new request received at " + Date.now());
    
         //This function call is very important. It tells that more processing is
         //required for the current request and is in the next middleware
         function/route handler.
         next();
        });
    
        app.listen(3000);`
    
  • To restrict it to a specific route (and all its subroutes), provide that route as the first argument of app.use()

  • One of the most important things about middleware in Express is the order in which they are written/included in your file; the order in which they are executed, given that the route matches also needs to be considered

  • Third Party Middleware

    • body-parser
      • This is used to parse the body of requests which have payloads attached to them `var bodyParser = require('body-parser');

          //To parse URL encoded data
         app.use(bodyParser.urlencoded({ extended: false }))
        
         //To parse json data
         app.use(bodyParser.json())`
        
    • cookie-parser
      • It parses Cookie header and populate req.cookies with an object keyed by cookie names

          `var cookieParser = require('cookie-parser');
           app.use(cookieParser())`
        

Video

Additional Resources

Clone this wiki locally