问题描述
我是javascript,nodejs和express的新手,对使用 next()
感到困惑.
我希望我的代码使用 next()
移至下一个路由器,但它似乎移至下一个 then
.
我的代码:
//验证router.post('/requests',(req,res,next)=> {让{myData} = req.bodybasicCheck(res,cluster,myData).then(()=> {如果(myCheck()){下一个()return//不需要执行其余的代码.只需转到下一个路由器即可.}...返回Promise.all(somePromises)}).then(()=> {...返回Promise.all(somePromises)}).then(()=> {如果(someCheck(){下一个()} 别的 {res.status(400).send('message')//我的代码到了!即使myCheck()为true}}).catch((err)=> {...})})//需要next()的位置router.post('/requests',(req,res)=> {...})
当 next()
在 basicCheck
之外时, next()
转到下一个router.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");下一个()}函数secondMiddleware(req,res,next){console.log("hello")res.send("hello");}app.get("/",firstMiddleware,secondMiddleware);
如您所见.在我的第一个中间件中,我使用 next()
.这告诉express.js在这种情况下转到下一个中间件 secondMiddleware
中间件从左到右执行,并使用 next()
告诉您移动到下一个,直到结束.
通常,最后一个中间件是您的API终结点,并且您不应该使用 next()
,否则您将跳出"目录.路线,并且如果您定义了全局错误处理程序,则会收到错误消息
也请注意:例如,通过创建一个名为 controller.js
的文件,可以分隔路线和逻辑.
function firstMiddleware(req,res,next){console.log("hy");下一个()}函数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",异步(req,res,next)= >> {让{myData} = req.body;让checkresult =等待awbasicCheck(res,cluster,myData);如果(myCheck()){返回next();}让someResults =等待Promise.all(somePromises);让someMoreResults =等待Promise.all(somePromises);如果(someCheck()){返回next();} 别的 {res.status(400).send("message");//我的代码到了!即使myCheck()为true}});
您使用 return
是,可以停止执行该函数,但是您也要做的是Promise链.
我在这里写了一个异步/等待方法
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()
?
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.
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
这篇关于ExpressJS将next()放在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!