fetch 改善了 XHR 又长又麻烦的写法,简化了程序码使阅读容易许多,而 fetch return 的是 Promise。
基本用法:let promise = fetch(url, [options])
,第二个参数为 method,body,headers...等,若没有第二个参数,则预设为 GET 请求。
例如:
const url = fetch("https://randomuser.me/api/?results=1");
console.log(url);
这时可以看到 fetch 回传的是 Promise 物件。
将 Prototype 展开,可以发现里面也有 catch()
,then()
,finally()
,Promise()
等。
而比较特别的地方是 PromiseResult 的 Response,我们将它展开,可以看到 HTTP 状态,如下图:
server 回传 response header:
- status 表示 HTTP 状态码。
- ok:true/false 表示成功与否,200-299 为 true。
- 要注意,使用 fetch 时,异常的 HTTP 状态,例如 404 或 500,并不会导致出现 error,而会正常 resolve,并把 ok status 设为 false,会让它发生 reject 的只有网路错误或其他会中断 request 的情况。
接着再将 Prototype 的 Response 展开,会发现里面有许多方法,如下图
为了获取 response body,我们要使用这些方法才能成功取得资料,而每次只能使用一种方法。
response.text()
读取 response,以文字形式回传 response。response.json()
将 response 转换为 JSON 格式来回传。response.formData()
以表单的形式回传 response。response.blob()
以 Blob 形式回传 response。response.arrayBuffer()
以 ArrayBuffer 形式回传 response。
例如:
使用 json()
,以 json 格式回传结果:
const url = fetch("https://randomuser.me/api/?results=1")
.then(response => response.json()) // 以 json 格式回传,这个 then 回传的结果会传入下一个参数
.then(results => console.log(results)) // 接收上一个 then 的结果,印出 json 格式资料
.catch(err => console.log(err))
结果如下
把上面的例子改成 text()
,以文字的格式回传结果:
const url = fetch("https://randomuser.me/api/?results=1")
.then(response => response.text()) // 以文字格式回传,这个 then 回传的结果会传入下一个参数
.then(results => console.log(results)) // 接收上一个 then 的结果,印出文字格式的资料
.catch(err => console.log(err))
结果如下
参考资料:
https://zh.javascript.info/fetch
https://mtr04-note.coderbridge.io/2020/09/07/about-fetch/
https://developer.mozilla.org/zh-TW/docs/Web/API/Fetch_API/Using_Fetch
<<: DAY10 - websocket前端实作-以vue.js为例
>>: 分类模型哪个好?confusion matrix/sensitivity/ specificity
我们都要谈Django了,总不能连他是什麽都不知道吧? 那既然你都诚心诚意地发问了,那我就大发慈悲地...
本文将於赛後同步刊登於笔者部落格 有兴趣学习更多 Kubernetes/DevOps/Linux 相...
今天是第三十天, 真的要写其实还有很多东西可以写, 但我的确累了, 铁人赛的这三十天像是兼两份差, ...
ChatOps with Mattermost chatops好处 成本低 互动性佳 即时反应提高效...
1-3简化指令电脑(SIC) 简介 简化指令电脑(Simplified Instructional ...