请原谅我,因为我对 Node JS/Express JS 很陌生
我有以下代码:
router.get('/:locationId', async (req, res) => {
console.log('[GET by _id] /locations/')
try{
const location = await Location.findById(req.params.locationId);
res.json(location);
}catch(err){
res.json({message:err, status:500});
}
});
router.get('/location_id/', async (req, res) => {
console.log('[GET by location_id] /locations/location_id')
});
每次我调用 localhost:3000/location_id/时,它都会调用第一个以“location_id”作为参数的函数。
我错过了什么吗?
最佳答案
快速路由和中间件是按顺序处理的函数的列表/数组/堆栈/队列。 Express 永远不会重新排列路由和中间件的顺序。
您有两条路线:
get('/:some_variable')
get('/location_id/')
第一条路线将始终匹配所有内容,因为 /location_id
也是可以分配给第一条路线的路径变量的有效字符串。
您可以通过重新安排首先处理的路由来使路由正常工作:
get('/location_id/')
get('/:some_variable')
关于node.js - Express JS 路由重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59450291/