我正在撰寫一個中間件函式,該函式將尋找驗證錯誤,如果發現錯誤,將給出一個特定的輸出,否則將繼續程式流程。我有兩個代碼相同的函式,但它們檢查的是不同的模式。
我的第一個函式運行時沒有任何例外。然而,當我試圖執行第二個函式時,我在控制臺中得到一個錯誤。
const validateCampground=(req, res, next)=> {
const { error } = campgroundSchema.validate(req.body)。
if (error) {
const msg = error.details.map((el) => /span> el. message).join(",")。
throw new ExpressError(msg, 400)。
} else {
next()。
}
};
const validateReview=(req, res, next)=> {
const { error } = reviewSchema.validate(req.body)。
if (error) {
const msg = error.details.map((el) => /span> el. message).join(",")。
throw new ExpressError(msg, 400)。
} else {
next(); //this is the point where the exception occurs。
}
};
只有在validateReview函式中,下一個中間件函式才不被識別為有效函式。
問題不是出在next()中間件上,而是出在路由上,因為我正在用validateReview函式來包裝路由。
我在做這樣的事情:
我在做這樣的事情。
app.post(
"/campgrounds/:id/reviews"。
validateReview(
catchAsync(async (req, res) => {
//my Logic here。
})
));
然而,我應該這樣做 :
app.post(
"/campgrounds/:id/reviews"。
驗證評論。
catchAsync(async (req, res) => {
//我的邏輯在這里。
})
);
uj5u.com熱心網友回復:
如果你想使用一個middileware
hi
exports。 middileware = (req,res,next) =>{
try{
//middileware logic
next()。
}catch(err){
//print the error。
})
}
}
并在 requires 檔案中呼叫匯出的middileware檔案,以檢查middileware函式
span class="hljs-keyword">const { middileware } = require('path'/span>)。
并這樣使用
router.get('/routename', middleware, nextfunction) //router you can choose as you like get, post, patch anything
試試這個
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/319822.html
標籤:


uj5u.com熱心網友回復: