Middleware in Express.js

Middleware in Express.js

The functions used in the request-response cycle known as middleware have access to the request and response object (req, res).

The Express.js routing layer calls many types of Express.js Middleware functions before to the actual request handler. Middleware, as its name suggests, sits between the initial request and the intended ultimate route. The sequence in which middleware functions are added determines how they are always called in stack.

To carry out activities like body parsing for URL-encoded or JSON requests, cookie parsing for fundamental cookie handling, or even dynamically creating JavaScript modules, middleware is frequently utilized.

A middleware function can perform the following tasks:

  • It is able to run any code.
  • It has the ability to modify both the request and response objects.
  • The request-response cycle can be finished.
  • The next middleware function in the stack can be called by it.

Middleware for Express.js

The list of middleware that might be utilized in an Express.js app is as follows:

  • middleware at the application level
  • middleware at the router level
  • middleware for managing errors
  • internal middleware
  • independent middleware

some basic example :

app.use((req, res, next) => {
  console.log('Time:', Date.now())
  next()
})        


app.post('/products', requireJsonContent, (request, response) => {
  ...
  ...
  response.json(...)
})        


app.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})        

要查看或添加评论,请登录

Md Joynul Abedin (Pavel)的更多文章

  • Why Data Structures and Algorithms Are Important ?

    Why Data Structures and Algorithms Are Important ?

    Array, Linked List, Stack, Queues, Searching, Sorting, Tree, Graph… Do you have questions that why should I study all…

  • System Design Cheatsheet

    System Design Cheatsheet

    Basic Steps Clarify and agree on the scope of the system User cases (description of sequences of events that, taken…

  • Linked List or Array ?

    Linked List or Array ?

    Today let's a simple discussion on two very basic and essential linear data structures every programmer should know..

  • Binary Tree: A Non-linear Data Structure (1)

    Binary Tree: A Non-linear Data Structure (1)

    A Binary Tree is a Tree data structure with two children or less. We commonly refer to them as the left and right child…

  • Contribution (PR) on GitHub Open Sources

    Contribution (PR) on GitHub Open Sources

    1. Fork the repository Fork the repository by clicking the fork button on the top of the page.

社区洞察

其他会员也浏览了