首页 > 解决方案 > 为什么带有参数的动词方法会阻塞另一个相同的路由?

问题描述

我正在通过写一些随机的东西来练习 node.js 和 express.js。所以在我写了一个带参数的get方法之后,它阻止了另一个get方法的运行。我想知道为什么。

我确信这是因为第一种方法。我删除它并在第二个之后移动它,它工作得很好。但是当它在2号之前,它阻止了它。

// the following code is the one that blocks
app.get("/animes/:id", (req, res)=>{
res.send(animes[req.params.id]);
});

app.get("/animes/add", (req, res)=>{
console.log(req.query);
res.send("yes")
}); 

// the following code works fine
app.get("/animes/add", (req, res)=>{
console.log(req.query);
res.send("yes")
});

app.get("/animes/:id", (req, res)=>{
res.send(animes[req.params.id]);
});

我还有另外两种获取方法,例如“/”和“animes”。我确信它们不是它阻塞的原因。

标签: javascriptnode.jsexpress

解决方案


中间件按照它们注册的顺序进行评估。

因此对于:

app.get("/animes/:id", ... )
app.get("/animes/add", ... )

Express 将首先测试请求的 url 是否匹配/animes/:id并将/animes/:idmatch /animes/add,注册的中间件app.get("/animes/add", ... )将永远无法到达。


推荐阅读