javascript - 使用 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');
});
你可以在这里找到我的示例代码。
解决方案
您的 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');
});
推荐阅读
- html - 分隔线的渲染宽度的仅 Chrome 可变性
- git - 从错误分支恢复合并后无法从另一个远程拉取
- html - 前端网页的编码问题 - HTML/CSS 编码
- java - 如何从另一个数组返回具有某个 int 索引的数组
- python - 日期时间以奇怪的格式打印
- javascript - 箭头转换/转换并单击链接
- python - tf2onnx Tensorflow 到 Onnx 输出不一致
- python - Fastapi + 草莓 GraphQL
- freeswitch - freeSwitch ESL api api 发起响应 -ERR NORMAL_CLEARING
- nginx - Nginx 位置、重写、上游和 proxy_pass 问题,无法访问 URL