JavaScript使用Fetch API获取接口响应后如何筛选指定字段?
代码问题与修正方案
现有代码的问题
- 混用async/await语法与
.then链式调用,逻辑冲突:你在await fetch阶段已经通过.then(res => res.json())将响应解析为JSON数组,此时得到的response变量已经是纯数据,不是Response对象,后续调用response.json()会直接抛出类型错误。 - 缺少字段提取逻辑,直接返回接口全量数据,没有筛选出你需要的
name、numberOfPages、released三个字段。
修正后可运行代码
const fetch = require("cross-fetch"); const URL = "https://anapioficeandfire.com/api/books" // Important: Don't change the function name const getBooks = async () => { // 发起接口请求获取响应对象 const response = await fetch(URL); // 校验请求是否成功,避免接口异常导致代码崩溃 if (!response.ok) { throw new Error(`请求失败,状态码:${response.status}`); } // 解析响应为全量JSON数据 const rawBookList = await response.json(); // 遍历数据仅保留需要的三个字段 return rawBookList.map(item => ({ name: item.name, numberOfPages: item.numberOfPages, released: item.released })); } getBooks().then(books => console.log(books))
输出说明
运行代码后返回的数组结构完全匹配你要求的格式,每一项仅包含指定的三个字段。
内容的提问来源于stack exchange,提问作者Faruk Şirket
相关产品推荐
相关产品推荐

