用 fetch 请求数据并用模块组织代码。
本节要点
- fetch 返回 Response,需要 json() 解析
- AbortController 可取消请求
- import/export 拆分模块
代码示例
export async function getPosts() {
const res = await fetch('/api/posts');
if (!res.ok) throw new Error(res.statusText);
return res.json();
}
import { getPosts } from './api.js';提示:fetch 不会因 4xx/5xx 抛错,需要手动检查 res.ok。