NodeJS / Express: what is “app.use”?

后端 未结 23 1329
别跟我提以往
别跟我提以往 2020-11-29 14:48

In the docs for the NodeJS express module, the example code has app.use(...).

What is the use function and where is it defined?

23条回答
  •  無奈伤痛
    2020-11-29 15:28

    app.use applies the specified middleware to the main app middleware stack. When attaching middleware to the main app stack, the order of attachment matters; if you attach middleware A before middleware B, middleware A will always execute first. You can specify a path for which a particular middleware is applicable. In the below example, “hello world” will always be logged before “happy holidays.”

    const express = require('express')
    const app = express()
    
    app.use(function(req, res, next) {
      console.log('hello world')
      next()
    })
    
    app.use(function(req, res, next) {
      console.log('happy holidays')
      next()
    })
    

提交回复
热议问题