首页 > 解决方案 > Express JS 路由重定向

问题描述

请原谅我,因为我对 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”作为参数调用第一个函数。

我错过了什么吗?

标签: node.jsexpress

解决方案


Express 路由和中间件是按顺序处理的函数的列表/数组/堆栈/队列。Express 从不重新排列路由和中间件的顺序。

你有两条路线:

get('/:some_variable')
get('/location_id/')

第一条路线将始终匹配所有内容,因为/location_id它也是可以分配给第一条路线的路径变量的有效字符串。

您可以通过重新安排首先处理哪个路由来使路由正常工作:

get('/location_id/')
get('/:some_variable')

推荐阅读