W
W
Wynell_ru2019-06-17 23:58:50
JavaScript
Wynell_ru, 2019-06-17 23:58:50

How does .use (middleware handler) work?

Already in several libraries, I discovered the ability to embed middleware, and I became interested in how this function works from the inside .use
Therefore, I decided to ask a question here.
So, how does .use - the middleware handler - work from the inside? Can I have examples of the source code of .use (sorry, I googled superficially, I didn’t find it)?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
H
hzzzzl, 2019-06-18
@Wynell_ru

here, I wrote my express with middleware

class Express {
  response = {}
  middles = []

  use = func => this.middles.push(func)

  get = () => {
    this.middles.forEach(func => func(this.response))
    console.log('RESPONSE NOW: ',this.response)
  }
}

app = new Express()
app.get()
// response: {}

function addBla(res) { res.bla = 17 }
// миддлвар добавляет какое-то свойство в response от сервера

app.use(addBla)
app.get()
// response: {bla: 17}

M
Mikhail Osher, 2019-06-18
@miraage

Under the hood, all kinds of express use https://www.npmjs.com/package/connect , and he already drives everything

A
Anton Spirin, 2019-06-18
@rockon404

app.use
router.use

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question