我是javascript、nodejs和express的新手,对使用next()
感到困惑。
我希望我的代码使用next()
移动到下一个路由器,但它似乎要移动到下个then
。
我的代码:
//validation
router.post('/requests', (req, res, next) => {
let {myData} = req.body
basicCheck(res, cluster, myData)
.then(() => {
if (myCheck()) {
next()
return // Doesn't need to do rest of the code. Just move on to the next router.post
}
...
return Promise.all(somePromises)
})
.then(() => {
...
return Promise.all(somePromises)
})
.then(() => {
if (someCheck() {
next()
} else {
res.status(400).send('message') // My code reaches here! even when myCheck() is true
}
})
.catch((err) => {
...
})
})
// where next() needs to be
router.post('/requests', (req, res) => {
...
})
当next()
在basicCheck
之外时,next()
转到下一个路由。post。
我不知道next()
在哪里。
在basicCheck()
中执行myCheck()
时,如何更正此代码?
使用next()
,您可以进入下一个中间件。
示例:
你有一条类似的路线:
app.get("/", (req, res, next) => {
res.send("hello")
})
您可以声明一个函数并像一样使用它,而不是使用匿名函数
function firstMiddleware(req, res, next){
res.send("hello")
}
app.get("/", firstMiddleware);
你能做的是,你可以在你的路线上有多个中间件,比如:
function firstMiddleware(req, res, next){
console.log("hy");
next()
}
function secondMiddleware(req,res,next) {
console.log("hello")
res.send("hello");
}
app.get("/", firstMiddleware, secondMiddleware);
正如你所看到的。在我的第一个中间件中,我使用next()
。这告诉express.js在这种情况下移动到下一个中间件secondMiddleware
中间件从左到右执行,使用next()
,您可以告诉它们移动到下一个,直到您到达最后。
通常最后一个中间件是您的API端点,您不应该使用CCD_;跳出";如果你定义了一个全局错误处理程序,你会收到一个错误
另请注意:一个额外的好处是通过创建一个名为controller.js
的文件来分离路由和逻辑。
controller.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
}
现在你可以导入它:
const { firstMiddleware, secondMiddleware } = require("./controller.js");
app.get("/", firstMiddleware, secondMiddleware);
随着的增长,这使您的代码更容易维护
编辑:
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
开关是可以停止函数的执行,但您所做的也是一个承诺链接。
我在这里写了一个异步/等待方法