我正在使用 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');
});
你可以找到我的sample code here .
最佳答案
您的 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');
});
关于javascript - 使用 Fetch API 时出现此错误 : Uncaught (in promise) TypeError: packages. map 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57716481/