Where does next() go in Express js?

强颜欢笑 提交于 2021-01-29 09:02:17

问题


I'm new to javascript, nodejs, and express, and confused of using next().

I want my code to move on to the next router with next(), but it seems to move on to the next then.

My code:


//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) => {
    ...
})

When next() is outside the basicCheck, next() goes to the next router.post.

I don't get the concept of where next() indicates.

How can I correct this code while doing myCheck() inside basicCheck()?


回答1:


With next() you move to the next middleware.

Exapmle:

You have a route like:

app.get("/", (req, res, next) => {
   res.send("hello")
})

Instead of using an anonymous function you can declare an function and use it it like:

function firstMiddleware(req, res, next){
   res.send("hello")
}

app.get("/", firstMiddleware);

What you can do is you can have multiple middlewares in your route like:

function firstMiddleware(req, res, next){
   console.log("hy");
   next()
}

function secondMiddleware(req,res,next) {
   console.log("hello")
   res.send("hello");
}

app.get("/", firstMiddleware, secondMiddleware);

As you can see. In my first middleware i use next(). This tells express.js to move to the next middleware in this case secondMiddleware

The middlewares gets executed from the left to right and with next() you tell them to move to the next until you are on the end.

Usually the last middleware is your API endpoint and you should not use next() otherwise you would "jump out" of your route and you would receive an error if you have defined an global error handler

Also sidenote: A bonus would be to seperate your routes and logic by creating an file called controller.js for example.

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
}

Now you can import it:

const { firstMiddleware, secondMiddleware } = require("./controller.js");

app.get("/", firstMiddleware, secondMiddleware);

This makes your code easier to maintain as it grows

EDIT:

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
  }
});

You use return witch yes stops the function from execution BUT what you also do is an promise chaining.

I have written here an async / await approach



来源:https://stackoverflow.com/questions/65069404/where-does-next-go-in-express-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!