Node.js中使用Axios请求接口时如何过滤返回的JSON数据?
实现方案
这里提供两种可行方案,优先推荐第一种,性能更好:
方案1:请求Pipedrive接口时直接过滤(推荐)
Pipedrive的交易接口本身支持status查询参数,直接在请求地址中添加即可,无需拉取全量数据再做本地过滤:
async getAllDeals(_, res){ try { // 请求URL新增status=won参数,直接获取符合要求的交易数据 const response = await axios.get(`${PIPE_URL}?api_token=${PIPE_TOKEN}&status=won`) return res.json(response.data) } catch (err) { console.log(err) // 补充错误响应,方便前端感知异常 return res.status(500).json({error: '获取交易数据失败'}) } }
方案2:拉取全量数据后本地过滤
如果有其他业务逻辑需要先拿到全量交易数据再处理,可以用JS原生数组的filter方法过滤:
async getAllDeals(_, res){ try { const response = await axios.get(`${PIPE_URL}?api_token=${PIPE_TOKEN}`) // 过滤status为won的交易条目 const wonDeals = response.data.filter(deal => deal.status === 'won') return res.json(wonDeals) } catch (err) { console.log(err) return res.status(500).json({error: '获取交易数据失败'}) } }
原有错误代码的问题说明
res.json(response.data)是响应输出方法,调用后会直接将全量数据返回给客户端,无法再做后续数据处理,且该方法的返回值不是交易数组,不能用来做过滤源数据- axios返回的
response对象不存在where方法,JS数组过滤统一使用filter方法即可
内容的提问来源于stack exchange,提问作者Marco Targino
相关产品推荐
相关产品推荐

