你好,我正在創建一個驗證中間件,但問題是我有 2 種型別到同一個端點,所以我為每個型別創建了兩個模式。
所有我想要做的就是當型別的財產以后通過通middleware_a esle回報middleware_b
這是我的想法,但它不起作用
const middlewareStrategy = (req,res,next) => {
if(req.params.type === "Something"){
return custom_middleware(schemas.A_body);
}
return custom_middleware(schemas.B_body);};
這里的 A_Body 只是驗證模式。
uj5u.com熱心網友回復:
很難準確地說出您想要做什么,因為您沒有顯示實際的中間件代碼,但是您可以通過幾種不同的方式動態選擇中間件。
動態呼叫所需的處理函式
const middlewareStrategy = (req,res,next) => {
const schema = req.params.type === "Something" ? schemas.A_body : schemas.B_body;
bodyStrategy(schema, req, res, next);
};
在這個中間件中,您正在動態呼叫 bodyStrategy 函式,該函式接受架構和 res, res, next 以便它可以充當中間件,但會知道架構。
創建一個在req物件上設定架構的中間件
const middlewareStrategy = (req,res,next) => {
req.schema = req.params.type === "Something" ? schemas.A_body : schemas.B_body;
next();
};
然后,像這樣使用它:
// this sets req.schema to be used by later middleware
app.use(middlewareStrategy);
然后,您可以使用另一個期望找到該req.schema屬性的中間件來完成其作業:
// this middleware uses req.schema
app.use(customMiddleware);
如果這不正是您要找的,那么請包含您的實際中間件的代碼,以便我們了解我們的真正目標。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/380245.html
上一篇:如何使用自己的身份驗證系統控制對GoogleCloudStorage物件的訪問?
下一篇:根據查詢條件從資料庫中檢索資料
