我试图通过检查url参数及其值(例如
)来过滤名称(或其他字段)的集合http://localhost:3000/patient?filter=name:jack
我有一个方法来检索url程序,并将其转换为json对象:
const filter = handleQueryFilter(req.query.filter)
const handleQueryFilter = (query) => {
try{
// convert the string to look like json object
// example id: -1, name: 1 to { id: "-1"}, {name: "1" }
const toJSONString = ("{" + query ).replace(/(w*[^:].$)/g, (matched => {
return '"' + matched.substring(0, matched.length ) + '"}' ;
}));
return JSON.parse(toJSONString);
}catch(err){
return JSON.parse("{}"); // parse empty json if the clients input wrong query format
}
}
从'handleQueryFilter'返回的内容将传递给'find'方法以从数据库中获取结果
let patients = await Patient.find(filter);
然而handleQueryFilter总是返回一个空对象(上面的catch部分),我做错了什么?
第一步:快速传递请求。使用
自动生成正文app.use(express.json())
编辑你的URL为:http://localhost:3000/patient?name=jack
您的replace
操作不应该做什么:
"{id: -1, name: 1".replace(/(w*[^:].$)/g, (matched => {
return '"' + matched.substring(0, matched.length ) + '"}'
}))
返回'{id: -1, name:" 1"}'
,这不是有效的JSON,因此JSON.parse
给出一个错误。
试试
Object.fromEntries("id: -1, name: 1".split(/,s*/).map(_=>_.split(/:s*/)))
的回报{id: '-1', name: '1'}
而不需要JSON.parse
。