简体   繁体   English

在路由处理程序中调用 function 与使用中间件

[英]Calling a function inside route handler vs using a middleware

I am trying to understand if there is any difference.我试图了解是否有任何区别。 I'll try to explain it with an example from express docs: https://expressjs.com/en/guide/using-middleware.html我将尝试使用 express 文档中的示例进行解释: https://expressjs.com/en/guide/using-middleware.html

function logOriginalUrl (req, res, next) {
  console.log('Request URL:', req.originalUrl)
  next()
}

function logMethod (req, res, next) {
  console.log('Request Type:', req.method)
  next()
}

const logStuff = [logOriginalUrl, logMethod]
app.get('/user/:id', logStuff, (req, res, next) => {
  res.send('User Info')
})

logOriginalUrl and logMethod are middlewares in this example. logOriginalUrl 和 logMethod 是本示例中的中间件。 What would happen if I write it like:如果我这样写会发生什么:

function logOriginalUrl() {
  console.log('Request URL:', req.originalUrl);
}

function logMethod() {
  console.log('Request Type:', req.method);
}

app.get('/user/:id', (req, res, next) => {
  logOriginalUrl();
  logMethod();
  res.send('User Info')
})

Is there any difference between these two?这两者有什么区别吗? This is a very simple example but it can be applied for any other example where you have to manipulate req or do anything else.这是一个非常简单的示例,但它可以应用于您必须操作 req 或执行其他任何操作的任何其他示例。

What is the difference between a middleware and calling + awaiting a function inside route handler?中间件和调用 + 等待路由处理程序内部的 function 有什么区别?

Theoretically, anything I can do as middleware, I feel like I can achieve exact same thing by awaiting same function in route handler function.从理论上讲,我可以作为中间件做的任何事情,我觉得我可以通过在路由处理程序 function 中等待相同的 function 来实现完全相同的事情。 So, what do I miss?那么,我错过了什么?

Your second code will throw an error because req is undefined in the scope of logOriginalUrl and logMethod .您的第二个代码将引发错误,因为reqlogOriginalUrllogMethod的 scope 中undefined

But if you would pass this data correctly, there would be absolutely no difference.但是,如果您正确传递此数据,则绝对没有区别。 Middlewares are for convenience.中间件是为了方便。

They are used to handle common scenarios betweem routes and make the code more readable.它们用于处理路由之间的常见场景并使代码更具可读性。

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

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