You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让json-server支持模糊关键词搜索并返回匹配结果?

json-server模糊搜索实现方案

你的问题出在请求格式不符合json-server的查询规则,当前写法无法触发模糊匹配逻辑。以下是两种直接可行的解决方案:

方案一:全局模糊搜索(匹配所有字段)

使用json-server内置的q参数,它会在所有字段中检索包含关键词的条目。同时注意修正axios响应数据的取值(数据存在response.data中):

getData : ( searchTerm : string ) => axios.get(`http://localhost:3000/books?q=${searchTerm}`)
  .then((response) => setData(response.data));

方案二:指定字段模糊搜索(仅匹配name字段)

如果只需要在name字段中做模糊匹配,使用_like后缀指定目标字段:

getData : ( searchTerm : string ) => axios.get(`http://localhost:3000/books?name_like=${searchTerm}`)
  .then((response) => setData(response.data));

额外优化:忽略大小写匹配

如果需要忽略关键词的大小写,在参数后添加_i后缀即可:

// 全局忽略大小写
getData : ( searchTerm : string ) => axios.get(`http://localhost:3000/books?q_i=${searchTerm}`)
  .then((response) => setData(response.data));

// 指定字段忽略大小写
getData : ( searchTerm : string ) => axios.get(`http://localhost:3000/books?name_like_i=${searchTerm}`)
  .then((response) => setData(response.data));

以上方案均支持部分匹配:不管输入car还是brand new car,只要内容中包含car关键词,就能正确返回对应的条目。

内容的提问来源于stack exchange,提问作者Himanshu Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 08:35:18