Express js 中的 next() 去了哪里?

我对 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()转到下一个 router.post。


我不明白哪里指示的概念next()。


myCheck()在内部执行操作时如何更正此代码basicCheck()?


慕码人2483693
浏览 217回答 1
1回答

慕的地8271018

随着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 端点,您不应该使用,next()否则您会“跳出”您的路线,并且如果您定义了全局错误处理程序,您将收到错误另请注意:一个好处是通过创建一个名为controller.jsexample 的文件来分离您的路线和逻辑。控制器.jsfunction 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“是”停止函数的执行,但您还做的是承诺链接。我在这里写了一个 async/await 方法
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript