Axios.all调用数组内多个链接发起GET请求报404错误如何解决
错误原因
- 核心问题是
Axios.get()传入的参数类型错误:你生成的data1数组每个元素都是包含PricingSummary属性的对象,不是直接的URL字符串。直接把对象传入Axios.get时,对象会被强制转为[object Object]字符串,拼接在当前站点域名后就形成了报错里的错误请求路径,触发404。 - 附加问题:从控制台打印可以看到
data1中存在PricingSummary为undefined的项,不处理的话也会导致无效请求。
正确实现方法
你可以直接修改请求逻辑,遍历的时候取对应URL属性,同时过滤无效项即可:
const callprice = () => { // 先过滤PricingSummary为空的无效项,再取出URL属性生成请求列表 const requestList = data1 .filter(item => item.PricingSummary) .map(item => Axios.get(item.PricingSummary)) Axios.all(requestList) .then(Axios.spread(function(...res) { // 原有的setState逻辑可以直接放在这里 console.log(res); })) // 建议补充异常捕获,避免单个请求失败导致整个流程中断 .catch(err => console.error('请求出错:', err)) };
如果需要简化后续使用逻辑,也可以在生成data1的时候直接存储URL字符串:
let data1 = []; console.log(data1); for (let Items of ItemsArray) { // 过滤空URL后直接存入数组,不需要嵌套对象 if (Items.pricingOptionsSummaryUrl) { data1.push(Items.pricingOptionsSummaryUrl); } }; // 此时请求逻辑可以简化为: const callprice = () => { Axios.all(data1.map(url => Axios.get(url))) .then(Axios.spread(function(...res) { console.log(res); })); };
内容的提问来源于stack exchange,提问作者Raiden Choong
相关产品推荐
相关产品推荐

