首页 > 解决方案 > 使用 Fetch API 时出现此错误: Uncaught (in promise) TypeError: packages.map is not a function

问题描述

我正在使用Fetch API从 API 的端点获取一些数据。

我收到此错误:

Uncaught (in promise) TypeError: package.map is not a function

我做了一些研究,似乎发生错误是因为响应是一个对象而不是数组。

这是一个代码示例:

 const url = 'https://reqres.in/api/users?page=2';

 const fetchPromise = fetch(url);

 fetchPromise.then(response => {

   return response.json();

 }).then(people => {

   // checks response value type
   console.log(typeof people);

   const names = people.map(person => person.name).join('\n');
 });

你可以在这里找到我的示例代码

标签: javascriptarraysobjectpromisefetch

解决方案


您的 API 端点https://reqres.in/api/users?page=2正在返回一个您map只能与数组一起使用的对象。我猜你想使用返回对象的数据字段,它是一个人员对象数组。

const url = 'https://reqres.in/api/users?page=2';

 const fetchPromise = fetch(url);

 fetchPromise.then(response => {

   return response.json();

 }).then(people => {

   // checks response value type
   console.log(typeof people);

   const names = people.data.map(person => person.first_name).join('\n');
 });

推荐阅读