[Express] Basic concept notes

Middleware (handlers)

  • Order-sensitive
  • Triggered by previous MW next()
  • Every middleware should call next() or end the request-response cycle
  • Changes to req and res will be passed down
  • App level MW: Bind to app
  • Router level MW: Bind to express.Router()
    • next('route'): Bypass remaining route callbacks
    • next('router'): Bypass remaining routes
  • Error-handling MW: (err, req, res, next) => { … }

Error handling

  • When an error occurs with next(myErr), remaining non-error MW will be skipped
  • Synchronous code: throw error;
  • Asynchronous code
    • Express 4: next(error);
    • Express 5: automatically call next(error);

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *