【问题标题】:How NodeJS middlewares works?NodeJS 中间件是如何工作的?
【发布时间】:2021-05-27 20:34:18
【问题描述】:

我的问题是为什么console.log("after middleware") 只打印一次,而app.use(foo) 在每次重新加载页面后都会调用。尽管页面重新加载,但在控制台中使用 npm start 后是否会解释一次使用 NodeJS 代码?

const express = require('express')
const app = express()

function foo(req, res, next) {
    console.log("middleware1")
    next()
}

app.use(foo)
console.log("after middleware");

app.get('/', function(req,res){
    res.send("main page")
})

app.listen(3000)

【问题讨论】:

    标签: javascript node.js express middleware


    【解决方案1】:

    基本上,为了简化一点,app.use() 是一个监听器,每次访问页面时都会调用它。另一方面,console.log() 是常规代码,仅在您的代码运行时调用一次。

    【讨论】:

      【解决方案2】:

      中间件是返回函数的函数。 示例:

      function myCustomMiddleware(x) {
         
        return function (req, res, next) {
          // This returned function can access to 'x' variable
          console.log(x)
          next() // Continue to the controller function.        
        }
      }
      
      app.get('/', myCustomMiddleware("Hello"), function(req,res){
        res.send("main page")
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-02
        • 1970-01-01
        • 2016-02-13
        • 1970-01-01
        • 2019-10-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多