问题描述
我搜索了一下,但没有找到要搜索的内容。 我有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',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?
})
我将如何做这些事情(如果可行的话)还是应该避免这样的代码?如果应该避免这样的代码,除了将一个函数的代码放入另一个函数之外,我还能做些什么。
解决方法
您可以通过这种方式更改设置路由器的方式,您可以像这样应用尽可能多的中间件:
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,next) => {
//do some coding
data = req.something
//get data from last middeleware
res.json({})
}
,同时您可以访问两个中间件中的所有req数据