簡體   English   中英

我可以將一個函數的參數(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({})
}

同時您可以訪問兩個中間件中的所有請求數據

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM