node.js - 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”作为参数调用第一个函数。
我错过了什么吗?
解决方案
Express 路由和中间件是按顺序处理的函数的列表/数组/堆栈/队列。Express 从不重新排列路由和中间件的顺序。
你有两条路线:
get('/:some_variable')
get('/location_id/')
第一条路线将始终匹配所有内容,因为/location_id
它也是可以分配给第一条路线的路径变量的有效字符串。
您可以通过重新安排首先处理哪个路由来使路由正常工作:
get('/location_id/')
get('/:some_variable')
推荐阅读
- wpf - 将背景颜色数据网格更改为 mahapp wpf
- actionscript-3 - 我想用动画 AS3 制作一个射击游戏,我坚持使用这段代码
- javascript - 读取 txt 文件,使用 Node 模块运行文本过滤器并使用 NodeJS 写入新的 .txt 文件
- r - 如何计算向量中的渐进平均值但在满足条件时重新启动?
- thorntail - 石英调度器 thorntail
- php - Magento 2:添加多个自定义选项来引用
- maven - 黄瓜 rhtml eport 未在硒黄瓜中以有效格式生成
- mysql - 我在 Google BigQuery 中的表“在美国位置找不到”
- ios - 有什么方法可以阻止 SwiftUI Text 显示椭圆?
- java - Hazelcast sql 查询