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

使用Fetch API与async/await获取用户列表时map报错问题

问题解决:TypeError: response.map is not a function

错误原因

你调用的API返回的是一个包含数组的对象,而非直接返回数组。该接口的实际返回结构如下:

{
  "page": 1,
  "per_page": 6,
  "total": 12,
  "total_pages": 2,
  "data": [/* 用户数据数组 */]
}

你直接对整个返回对象response调用map方法,但对象本身没有map属性,因此抛出类型错误。

修正后的代码

1. 修复数据处理逻辑

先提取response.data(真正的用户数据数组),再使用map方法:

async function getData() {
    const response = await (await fetch("https://reqres.in/api/users?page=1")).json();
    // 提取data数组后再执行map
    return response.data.map(user => user.id);
}

getData()
    .then(data => {
        console.log(data[0]); // 现在会正常输出第一个用户的ID
    })
    .catch(err => console.error(err)); // 建议添加异常捕获,避免程序崩溃

2. 完整实现:将用户列表渲染到HTML页面

如果要完成“把用户列表展示在页面”的需求,可扩展代码如下:

<!DOCTYPE html>
<html>
<head>
    <title>用户列表展示</title>
</head>
<body>
    <div id="user-container"></div>

    <script>
        async function fetchUsers() {
            const response = await (await fetch("https://reqres.in/api/users?page=1")).json();
            return response.data;
        }

        async function renderUserList() {
            const container = document.getElementById('user-container');
            try {
                const users = await fetchUsers();
                // 生成用户卡片HTML字符串
                const userCards = users.map(user => `
                    <div style="border: 1px solid #ddd; padding: 12px; margin: 10px; border-radius: 6px; width: 200px; display: inline-block;">
                        <img src="${user.avatar}" alt="${user.first_name}" style="width: 80px; height: 80px; border-radius: 50%;">
                        <h4>${user.first_name} ${user.last_name}</h4>
                        <p>邮箱:${user.email}</p>
                        <p>用户ID:${user.id}</p>
                    </div>
                `).join('');
                container.innerHTML = userCards;
            } catch (error) {
                container.innerHTML = `<p>加载用户列表失败:${error.message}</p>`;
            }
        }

        // 页面加载完成后渲染列表
        renderUserList();
    </script>
</body>
</html>

关键提示

  • 调用第三方API时,先通过console.log(response)确认返回结构,不要默认返回就是数组。
  • 异步操作必须添加错误捕获,避免因接口异常导致页面功能完全失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 06:25:06