使用Fetch API提取属性渲染到HTML时无法为img元素赋值src
问题原因
- Promise链式调用未正确传递返回值:第二个
.then()回调仅执行了console.log(data[0].imageUrl),没有显式返回接口返回的数组data,导致下一个链式调用的.then()接收到的replaceImageSrc值为undefined,执行undefined[0]会直接抛出错误,赋值逻辑不会生效。 - 当前代码仅设计了单张图片的处理逻辑,无法匹配接口返回的5条商品数据。
修复方案
批量渲染所有商品图片(推荐,匹配你的HTML结构)
const getImgUrl = fetch('http://localhost:3000/api/cameras'); getImgUrl .then(response => response.json()) .then(data => { // 遍历商品数组,批量给对应img元素赋值src data.forEach((product, index) => { const img = document.getElementById(`img-art-${index + 1}`); if (img) img.src = product.imageUrl; }); }) .catch(error => console.log("Erreur" + error))
仅渲染第一张图片的简化写法
如果你暂时只需要处理第一张图片,也可以把打印和赋值逻辑合并到同一个回调内,避免Promise返回值传递问题:
const img = document.getElementById("img-art-1"); const getImgUrl = fetch('http://localhost:3000/api/cameras'); getImgUrl .then(response => response.json()) .then(data => { console.log(data[0].imageUrl); img.src = data[0].imageUrl; }) .catch(error => console.log("Erreur" + error))
内容的提问来源于stack exchange,提问作者El_Michel
相关产品推荐
相关产品推荐

