axios 使用技巧
中文文档:http://www.axios-js.com/zh-cn/docs/
对比 fetch()
先看官方 API 介绍:
- fetch: https://developer.mozilla.org/zh-CN/docs/Web/API/fetch
- response: https://developer.mozilla.org/zh-CN/docs/Web/API/Response
对错误处理与原生 fetch 有重要区别
fetch 不管 response.status 是多少(200/400...),都会走 then。
而 axios 只有 200 才会走 then。
fetch 返回的 res.body 是 readableStream 不能直接用
若提前知道 body 的是文本内容,可用 const bodyText = await res.text() 去获取。注意,text() 返回的是个 Promise。
若 body 是文件下载等流类型,可以手动 res.body.getReader() 做二次处理。