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

调用Unsplash图片搜索API报photos.forEach is not a function错误如何解决

问题根因

你调用的Unsplash搜索API/search/photos返回的响应数据不是直接的图片数组,而是包含分页元数据、结果列表的对象,实际图片数组存放在返回对象的results字段中。你直接将整个返回对象传入GenerateHTML方法调用forEach,非数组类型不存在forEach方法,因此抛出该类型错误。

修复方案
  • 调整接口返回值的取值逻辑,取results字段的图片数组传入渲染方法,同时删除字符串拼接前多余的await(字符串拼接为同步操作,无需等待):
async getSearchedImages(e){
    e.preventDefault();
    const searchValue = e.target.querySelector('input').value;
    const baseURL = `https://api.unsplash.com/search/photos?page=1&query=${searchValue}&client_id=${this.API_KEY}`
    const res = await this.fetchImages(baseURL);
    this.GenerateHTML(res.results);
}
  • 补充渲染方法的参数容错判断,避免接口异常返回非预期结构时重复报错:
GenerateHTML(photos){
    if(!Array.isArray(photos)) return;
    photos.forEach(photo => {
        const item = document.createElement('div');
        item.classList.add('item');
        item.innerHTML = `
        <a href='#'>
            <img src="${photo.urls.small}">
            <h3>${photo.user.name}</h3>
        </a>             
        `;
        this.galleryDiv.appendChild(item);
    });
}
  • 可选优化:在请求方法中补充接口请求状态判断,提前捕获请求失败场景:
async fetchImages(baseURL){
    const response = await fetch(baseURL, {
        method: 'GET',
        headers:{
            Accept: 'application/json',
            Authorization: this.API_KEY
        }
    });
    if(!response.ok) throw new Error(`请求失败,状态码:${response.status}`);
    const photos = await response.json();
    return photos;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:09:03