1 回答

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
隨著next()您移動(dòng)到下一個(gè)中間件。
示例:
你有這樣的路線(xiàn):
app.get("/", (req, res, next) => {
res.send("hello")
})
您可以聲明一個(gè)函數(shù)并使用它,而不是使用匿名函數(shù),如下所示:
function firstMiddleware(req, res, next){
res.send("hello")
}
app.get("/", firstMiddleware);
您可以做的是您的路線(xiàn)中可以有多個(gè)中間件,例如:
function firstMiddleware(req, res, next){
console.log("hy");
next()
}
function secondMiddleware(req,res,next) {
console.log("hello")
res.send("hello");
}
app.get("/", firstMiddleware, secondMiddleware);
如你看到的。在我的第一個(gè)中間件中,我使用next(). 在這種情況下,這告訴express.js移動(dòng)到下一個(gè)中間件secondMiddleware
中間件從左到右執(zhí)行,next()您告訴它們移動(dòng)到下一個(gè),直到最后。
通常最后一個(gè)中間件是您的 API 端點(diǎn),您不應(yīng)該使用,next()否則您會(huì)“跳出”您的路線(xiàn),并且如果您定義了全局錯(cuò)誤處理程序,您將收到錯(cuò)誤
另請(qǐng)注意:一個(gè)好處是通過(guò)創(chuàng)建一個(gè)名為controller.jsexample 的文件來(lái)分離您的路線(xiàn)和邏輯。
控制器.js
function firstMiddleware(req, res, next){
console.log("hy");
next()
}
function secondMiddleware(req,res,next) {
console.log("hello")
res.send("hello");
}
module.exports = {
firstMiddleware,
secondMiddleware
}
現(xiàn)在您可以導(dǎo)入它:
const { firstMiddleware, secondMiddleware } = require("./controller.js");
app.get("/", firstMiddleware, secondMiddleware);
這使得您的代碼隨著代碼的增長(zhǎng)而更容易維護(hù)
編輯:
router.post("/requests", async (req, res, next) => {
let { myData } = req.body;
let checkresult = await awbasicCheck(res, cluster, myData);
if (myCheck()) {
return next();
}
let someResults = await Promise.all(somePromises);
let someMoreResults = await Promise.all(somePromises);
if (someCheck()) {
return next();
} else {
res.status(400).send("message"); // My code reaches here! even when myCheck() is true
}
});
您使用return“是”停止函數(shù)的執(zhí)行,但您還做的是承諾鏈接。
我在這里寫(xiě)了一個(gè) async/await 方法
添加回答
舉報(bào)