app.get("/:id",(req,res)=>{}) 处理应用程序路由中具有的端点的每个调用

问题描述 投票:0回答:1

我面临一个问题。我已经在应用程序路线中创建了一个端点。有一个终点

app.get("/:id",(req,res)=>{
console.log(req.params)
})

还有一些端点,如 localhost:2000/abclocalhost:2000/abfh 等。

问题是当我调用其他端点(例如 localhost:2000/abc)时, localhost:2000/:id 也会在对其他端点的每次调用中接受请求。 取id值为

{ id: 'favicon.ico' }

如何预防?

有什么解决办法吗?

picture

node.js express
1个回答
0
投票

根据提供的信息,我确信您已首先在您的

app.js
中定义了这一点。

app.get("/:id",(req,res)=>{
   console.log(req.params)
})

然后你为这些网址定义了路由,如

localhost:2000/abc
 localhost:2000/abfh

因此,由于

parametric-route
(在您的情况下为
'/:id'
)首先在
fixed-path
之前定义(即
/abc
/abfh
),默认情况下,
parametric-path
优先于
fixed-path
定义,并且优先。

这就是当您请求其他

endpoint
时,它会通过此
/:id
路线接收的原因。

欲了解更多信息,您可以查看以下链接。

https://gabrieleromanato.name/order-of-routes-when-using-parameters-in-expressjs#:~:text=ExpressJS%20calculates%20the%20priority%20of,')()%3B%20app .

© www.soinside.com 2019 - 2024. All rights reserved.