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

使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 15:30:00