【问题标题】:Can I pass the parameters (req, res, next) of a function to another function?我可以将一个函数的参数(req、res、next)传递给另一个函数吗?
【发布时间】:2026-02-08 22:10:02
【问题描述】:

我搜索了一下,但没有找到我要搜索的内容。 我有 Node 应用程序和两个功能:

router.get('/get/user-relevant-data', (req,res,next)=>{
    //some code is executed here
    return res.status(200).json(userRelevantData)
})
router.get('/get/updated-user', (req,res,next) => {
    // I want to call '/get/user-relevant-data' and assign the returned object to another variable
    let userRelevantData = // how to call the function here correctly?
})

我将如何做这样的事情(如果可行的话)还是应该避免这样的代码?如果应该避免这样的代码,除了将一个函数的代码放入另一个函数之外,我还能做什么。

【问题讨论】:

  • 重构一个加载数据的函数,从两个处理程序中调用它。
  • 您的意思是:在我的 Angular 应用程序中,我有一个服务可以获取更新的用户。因此,与其尝试将整个用户放在后端,我应该从上面调用这两个函数并在我的前端构造新用户?

标签: javascript node.js http parameter-passing router


【解决方案1】:

您可以更改设置路由器的方式,这样您就可以应用任意数量的中间件,如下所示:

const middleware1 = require("....") //adress to the file your middleware is located
const middleware2 = require("....") //adress to the file your middleware is located


router.get('/directory', middleware1, middleware2 )

在另一个文件中,您以这种方式定义中间件:

exports.middleware1 = (req, res, next) => {
   //do some coding
 req.something= someDataToPass
            next()   

//you add the data you want to pass to next middleware to the req obj
// and then access that in the next middleware from the req object then
// call next to run the next middleware

}

然后在另一个文件或同一个文件中键入另一个中间件,如下所示:

exports.middleware2 = (req, res, next) => {
   //do some coding
 data = req.something
//get data from last middeleware
res.json({})
}

同时您可以访问两个中间件中的所有 req 数据

【讨论】:

  • 我如何从中间件获取数据?例如,中间件返回一个对象,我将如何在 router.get-function 中获取和分配该对象?啊,所以我可以将对象附加到请求中。所以,中间件总是在路由器之前被调用。这是一个不错的方法,我会尝试!
  • 我忘了告诉你你不能在第一个中间件中调用 next 例如你可以在第一个中间件中有一个 if ,当用户未通过身份验证时它不会调用 next 并且你可以执行res.json 在第一个中间件中返回数据。但是一旦调用 res.json 就不能在下一个中间件中再次调用它