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

MERN应用中Axios响应过滤返回空数组问题求助

问题分析与修复

你的代码存在三个核心问题,直接导致过滤后返回空数组:

1. 不必要的数组嵌套

你将response.data额外嵌套了一层数组:const responseArray = [response.data],但从你提供的示例数据来看,response.data本身就是一个瓶子对象的数组,这会让数据变成二维数组,后续filter遍历的是外层数组的单个元素(整个瓶子数组),而非每个独立的瓶子对象。

2. 错误的过滤逻辑

bottle.includes(${query})完全不适用当前场景:

  • 若保留嵌套,bottle是整个瓶子数组,includes会检查数组内是否存在与query完全相等的元素,但query是字符串,数组内是对象,不可能匹配。
  • 即使去掉嵌套,bottle是对象,对象没有includes方法,你需要检查对象的具体属性(比如producer、wineName、region等)是否包含query字符串。

3. 返回值错误

return filteredResponseArray.data中,filteredResponseArray是过滤后的数组,根本不存在data属性,直接返回数组即可。


修正后的代码

const searchBottles = async (token, query) => {
  const config = {
    headers: {
      Authorization: `Bearer ${token}`
    }
  }

  try {
    const response = await axios.get(API_URL, config)
    // 直接使用response.data,本身就是瓶子对象的数组
    const bottles = response.data
    // 过滤逻辑:检查指定属性是否包含query(添加大小写不敏感处理更友好)
    const filteredBottles = bottles.filter(bottle => {
      // 可根据需求添加更多需要搜索的字段
      const searchableFields = [bottle.producer, bottle.wineName, bottle.region, bottle.variety]
      return searchableFields.some(field => 
        field.toLowerCase().includes(query.toLowerCase())
      )
    })

    return filteredBottles
  } catch (error) {
    console.log("SEARCH BOTTLES SERVICE ERROR: ", error)
  }
}

额外优化建议

  • 如果数据量较大,建议将过滤逻辑放在后端(通过MongoDB查询实现),前端过滤会浪费带宽与性能。
  • 可给搜索字段添加权重,比如优先匹配wineName再匹配producer。
  • 处理query为空的情况,直接返回全部数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:30:53