简体   繁体   English

NodeJS 中间件是如何工作的?

[英]How NodeJS middlewares works?

My question is why console.log("after middleware") is printing only once while app.use(foo) is calling after every page reload.我的问题是为什么console.log("after middleware")只打印一次,而app.use(foo)在每次页面重新加载后都调用。 Does using NodeJS code is interpreted one time after use npm start in console despite page reload?尽管页面重新加载,但在控制台中使用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)

Basically, to simplify it a little, app.use() is a listener, that is called every time the page is visited.基本上,为了简化一点, app.use()是一个监听器,每次访问页面时都会调用它。 The console.log() on the other hand is regular code that is called only once, when your code is run.另一方面, console.log()是常规代码,仅在运行代码时调用一次。

A middleware is a function that return a function.中间件是返回 function 的 function。 Example:例子:

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")
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM