gpt4 book ai didi

javascript - 使用 Fetch API 时出现此错误 : Uncaught (in promise) TypeError: packages. map 不是函数

转载 作者:行者123 更新时间:2023-11-28 14:15:23 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com