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

后端 未结 23 1421
别跟我提以往
别跟我提以往 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:06

    app.use is Application level middleware

    Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.

    you can use to check all requests, for example, you want to check token/access token you need to write a middleware by using app.use to check the token in the request.

    This example shows a middleware function with no mount path. The function is executed every time the app receives a request.

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

    reference from https://expressjs.com/en/guide/using-middleware.html

提交回复
热议问题