我可以将一个函数的参数(req、res、next)传递给另一个函数吗?
Can I pass the parameters (req, res, next) of a function to another function?
我搜索了一下,但没有找到我要搜索的内容。
我有 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?
})
我将如何做这些事情(如果可行的话)或者应该避免这样的代码?如果要避免这样的代码,我除了把一个函数的代码放到另一个函数中还能做什么。
您可以更改设置路由器的方式,您可以像这样应用任意数量的中间件:
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({})
}
同时您可以访问两个中间件中的所有请求数据
我搜索了一下,但没有找到我要搜索的内容。 我有 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?
})
我将如何做这些事情(如果可行的话)或者应该避免这样的代码?如果要避免这样的代码,我除了把一个函数的代码放到另一个函数中还能做什么。
您可以更改设置路由器的方式,您可以像这样应用任意数量的中间件:
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({})
}
同时您可以访问两个中间件中的所有请求数据