如何调用 Fetch API?

解读

面试官抛出“如何调用 Fetch API”时,真正想考察的是你对“浏览器端”与“Python 端”两种网络调用范式的区分能力。国内一线大厂(阿里、腾讯、字节、美团)的 Python 岗面试里,90% 的候选人会下意识把 Fetch 当成 Requests 的“别名”,直接背诵 requests.get 的用法,结果瞬间被标记为“概念混淆”。正确姿势是:先明确 Fetch 是浏览器原生异步 API,再用 Python 的“等价物”做迁移对比,才能体现你对“跨端网络栈”的通透理解。

知识点

  1. Fetch 是 Web 标准,不是 Python 库;它返回 Promise,必须配合 async/await 或 .then() 使用。
  2. Requests 是 Python 同步阻塞模型,对应 Fetch 的“同步写法”需借助 aiohttp 或 httpx.AsyncClient。
  3. 国内面试常追问的 3 个差异点:
    • CORS 预检由浏览器自动完成,Requests 侧需手动加 headers={'Origin': ...} 模拟。
    • Fetch 默认不携带 Cookie,credentials: 'include' 显式开启;Requests 的 Session 自动管理 Cookie。
    • Fetch 只有网络错误才 reject,HTTP 4xx/5xx 会 resolve 成功,需要 response.ok 二次判断;Requests 直接 raise_for_status()。
  4. 性能调优钩子:Fetch 可用 AbortController 实现超时;Python 侧用 httpx.Timeout(connect=5, read=10, write=10, pool=5) 精细控制。

答案

“Fetch 是浏览器提供的异步接口,调用范式分三步:

  1. 构造请求:
const ctrl = new AbortController();
const resp = await fetch('https://api.xxx.com/v1/order', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', 'X-Req-Id': uuid() },
  body: JSON.stringify({ skuId: 123 }),
  credentials: 'include',
  signal: ctrl.signal
});
  1. 错误处理:
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const data = await resp.json();
  1. 超时控制:
setTimeout(() => ctrl.abort(), 3000);

在 Python 侧,等价异步写法推荐使用 httpx.AsyncClient:

async with httpx.AsyncClient(timeout=10) as client:
    r = await client.post(
        'https://api.xxx.com/v1/order',
        json={'skuId': 123},
        headers={'X-Req-Id': uuid.uuid4().hex}
    )
    r.raise_for_status()
    data = r.json()

这样既展示了对 Fetch 的完整理解,也体现了 Python 生态的迁移能力。”

拓展思考

  1. Mock 场景:国内单元测试常禁用真实外网,可用 msw(Service Worker)在浏览器端拦截 Fetch,对应 Python 侧使用 responses 或 pytest-httpx 做镜像拦截,实现“双端同构”的测试套件。
  2. 流式下载:Fetch 通过 response.body.getReader() 手动读取 Uint8Array 流;Python 侧用 requests.get(url, stream=True) 或 httpx.stream("GET", url),结合生成器逐块落盘,可在 4G 弱网环境下把内存占用稳定在 30 MB 以内。
  3. 链路追踪:国内大厂全链路监控要求注入 sw8(SkyWalking)或 uber-trace-id 头,Fetch 需在 headers 显式携带,Python 侧通过 requests.Session 的 hooks={'response': inject_trace} 统一追加,保证跨语言调用 traceId 不丢失,这是高级 Python 开发晋升 P7/P8 的必备细节。