JavaScript使用Fetch的方法詳解
Fetch API 提供了一個(gè) JavaScript接口,用于訪問和操縱HTTP管道的部分,例如請(qǐng)求和響應(yīng)。它還提供了一個(gè)全局 fetch()
方法,該方法提供了一種簡(jiǎn)單,合理的方式來跨網(wǎng)絡(luò)異步獲取資源。
這種功能以前是使用 XMLHttpRequest
實(shí)現(xiàn)的。Fetch提供了一個(gè)更好的替代方法,可以很容易地被其他技術(shù)使用,例如 Service Workers
。Fetch還提供了單個(gè)邏輯位置來定義其他HTTP相關(guān)概念,例如CORS和HTTP的擴(kuò)展。
請(qǐng)注意,fetch
規(guī)范與jQuery.ajax()
主要有兩種方式的不同,牢記:
- 當(dāng)接收到一個(gè)代表錯(cuò)誤的 HTTP 狀態(tài)碼時(shí),從
fetch()
返回的 Promise 不會(huì)被標(biāo)記為 reject, 即使該 HTTP 響應(yīng)的狀態(tài)碼是 404 或 500。相反,它會(huì)將 Promise 狀態(tài)標(biāo)記為 resolve (但是會(huì)將 resolve 的返回值的ok
屬性設(shè)置為 false ),僅當(dāng)網(wǎng)絡(luò)故障時(shí)或請(qǐng)求被阻止時(shí),才會(huì)標(biāo)記為 reject。 - 默認(rèn)情況下,
fetch
不會(huì)從服務(wù)端發(fā)送或接收任何 cookies, 如果站點(diǎn)依賴于用戶 session,則會(huì)導(dǎo)致未經(jīng)認(rèn)證的請(qǐng)求(要發(fā)送 cookies,必須設(shè)置 credentials 選項(xiàng))。自從2017年8月25日后,默認(rèn)的credentials政策變更為same-origin
Firefox也在61.0b13中改變默認(rèn)值
進(jìn)行 fetch 請(qǐng)求
一個(gè)基本的 fetch請(qǐng)求設(shè)置起來很簡(jiǎn)單??纯聪旅娴拇a:
fetch('http://example.com/movies.json') .then(function(response) { return response.json(); }) .then(function(myJson) { console.log(myJson); });
這里我們通過網(wǎng)絡(luò)獲取一個(gè)JSON文件并將其打印到控制臺(tái)。最簡(jiǎn)單的用法是只提供一個(gè)參數(shù)用來指明想fetch()
到的資源路徑,然后返回一個(gè)包含響應(yīng)結(jié)果的promise(一個(gè) Response
對(duì)象)。
當(dāng)然它只是一個(gè) HTTP 響應(yīng),而不是真的JSON。為了獲取JSON的內(nèi)容,我們需要使用 json()
方法(在Body
mixin 中定義,被 Request
和 Response
對(duì)象實(shí)現(xiàn))。
注意:Body mixin 還有其他相似的方法,用于獲取其他類型的內(nèi)容。參考 Body。
最好使用符合內(nèi)容安全策略 (CSP)的鏈接而不是使用直接指向資源地址的方式來進(jìn)行Fetch的請(qǐng)求。
支持的請(qǐng)求參數(shù)
fetch()
接受第二個(gè)可選參數(shù),一個(gè)可以控制不同配置的 init
對(duì)象:
參考 fetch(),查看所有可選的配置和更多描述。
// Example POST method implementation: postData('http://example.com/answer', {answer: 42}) .then(data => console.log(data)) // JSON from `response.json()` call .catch(error => console.error(error)) function postData(url, data) { // Default options are marked with * return fetch(url, { body: JSON.stringify(data), // must match 'Content-Type' header cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: 'same-origin', // include, same-origin, *omit headers: { 'user-agent': 'Mozilla/4.0 MDN Example', 'content-type': 'application/json' }, method: 'POST', // *GET, POST, PUT, DELETE, etc. mode: 'cors', // no-cors, cors, *same-origin redirect: 'follow', // manual, *follow, error referrer: 'no-referrer', // *client, no-referrer }) .then(response => response.json()) // parses response to JSON }
發(fā)送帶憑據(jù)的請(qǐng)求
為了讓瀏覽器發(fā)送包含憑據(jù)的請(qǐng)求(即使是跨域源),要將credentials: 'include'
添加到傳遞給 fetch()
方法的init
對(duì)象。
fetch('https://example.com', { credentials: 'include' })
如果你只想在請(qǐng)求URL與調(diào)用腳本位于同一起源處時(shí)發(fā)送憑據(jù),請(qǐng)?zhí)砑?code>credentials: 'same-origin'。
// The calling script is on the origin 'https://example.com' fetch('https://example.com', { credentials: 'same-origin' })
要改為確保瀏覽器不在請(qǐng)求中包含憑據(jù),請(qǐng)使用credentials: 'omit'
。
fetch('https://example.com', { credentials: 'omit' })
上傳 JSON 數(shù)據(jù)
使用 fetch()
POST JSON數(shù)據(jù)
var url = 'https://example.com/profile'; var data = {username: 'example'}; fetch(url, { method: 'POST', // or 'PUT' body: JSON.stringify(data), // data can be `string` or {object}! headers: new Headers({ 'Content-Type': 'application/json' }) }).then(res => res.json()) .catch(error => console.error('Error:', error)) .then(response => console.log('Success:', response));
上傳文件
可以通過HTML<input type="file" />
元素,FormData()
和fetch()
上傳文件。
var formData = new FormData(); var fileField = document.querySelector("input[type='file']"); formData.append('username', 'abc123'); formData.append('avatar', fileField.files[0]); fetch('https://example.com/profile/avatar', { method: 'PUT', body: formData }) .then(response => response.json()) .catch(error => console.error('Error:', error)) .then(response => console.log('Success:', response));
上傳多個(gè)文件
可以通過HTML<input type="file" mutiple/>
元素,FormData()
和fetch()
上傳文件。
var formData = new FormData(); var photos = document.querySelector("input[type='file'][multiple]"); formData.append('title', 'My Vegas Vacation'); formData.append('photos', photos.files); fetch('https://example.com/posts', { method: 'POST', body: formData }) .then(response => response.json()) .then(response => console.log('Success:', JSON.stringify(response))) .catch(error => console.error('Error:', error));
檢測(cè)請(qǐng)求是否成功
如果遇到網(wǎng)絡(luò)故障,fetch()
promise 將會(huì) reject,帶上一個(gè) TypeError
對(duì)象。雖然這個(gè)情況經(jīng)常是遇到了權(quán)限問題或類似問題——比如 404 不是一個(gè)網(wǎng)絡(luò)故障。想要精確的判斷 fetch()
是否成功,需要包含 promise resolved 的情況,此時(shí)再判斷 Response.ok
是不是為 true。類似以下代碼:
fetch('flowers.jpg').then(function(response) { if(response.ok) { return response.blob(); } throw new Error('Network response was not ok.'); }).then(function(myBlob) { var objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }).catch(function(error) { console.log('There has been a problem with your fetch operation: ', error.message); });
自定義請(qǐng)求對(duì)象
除了傳給 fetch()
一個(gè)資源的地址,你還可以通過使用 Request()
構(gòu)造函數(shù)來創(chuàng)建一個(gè) request 對(duì)象,然后再作為參數(shù)傳給 fetch()
:
var myHeaders = new Headers(); var myInit = { method: 'GET', headers: myHeaders, mode: 'cors', cache: 'default' }; var myRequest = new Request('flowers.jpg', myInit); fetch(myRequest).then(function(response) { return response.blob(); }).then(function(myBlob) { var objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; });
Request()
和 fetch()
接受同樣的參數(shù)。你甚至可以傳入一個(gè)已存在的 request 對(duì)象來創(chuàng)造一個(gè)拷貝:
var anotherRequest = new Request(myRequest,myInit);
這個(gè)很有用,因?yàn)?request 和 response bodies 只能被使用一次(譯者注:這里的意思是因?yàn)樵O(shè)計(jì)成了 stream 的方式,所以它們只能被讀取一次)。創(chuàng)建一個(gè)拷貝就可以再次使用 request/response 了,當(dāng)然也可以使用不同的 init
參數(shù)。
注意:clone()
方法也可以用于創(chuàng)建一個(gè)拷貝。它在語義上有一點(diǎn)不同于其他拷貝的方法。其他方法(比如拷貝一個(gè) response)中,如果 request 的 body 已經(jīng)被讀取過,那么將執(zhí)行失敗,然而 clone()
則不會(huì)失敗。
Headers
使用 Headers
的接口,你可以通過 Headers()
構(gòu)造函數(shù)來創(chuàng)建一個(gè)你自己的 headers 對(duì)象。一個(gè) headers 對(duì)象是一個(gè)簡(jiǎn)單的多名值對(duì):
var content = "Hello World"; var myHeaders = new Headers(); myHeaders.append("Content-Type", "text/plain"); myHeaders.append("Content-Length", content.length.toString()); myHeaders.append("X-Custom-Header", "ProcessThisImmediately");
也可以傳一個(gè)多維數(shù)組或者對(duì)象字面量:
myHeaders = new Headers({ "Content-Type": "text/plain", "Content-Length": content.length.toString(), "X-Custom-Header": "ProcessThisImmediately", });
它的內(nèi)容可以被獲?。?/p>
console.log(myHeaders.has("Content-Type")); // true console.log(myHeaders.has("Set-Cookie")); // false myHeaders.set("Content-Type", "text/html"); myHeaders.append("X-Custom-Header", "AnotherValue"); console.log(myHeaders.get("Content-Length")); // 11 console.log(myHeaders.getAll("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"] myHeaders.delete("X-Custom-Header"); console.log(myHeaders.getAll("X-Custom-Header")); // [ ]
雖然一些操作只能在 ServiceWorkers
中使用,但是它提供了更方便的操作 Headers 的 API。
如果使用了一個(gè)不合法的HTTP Header屬性名,那么Headers的方法通常都拋出 TypeError 異常。如果不小心寫入了一個(gè)不可寫的屬性,也會(huì)拋出一個(gè) TypeError 異常。除此以外的情況,失敗了并不拋出異常。例如:
var myResponse = Response.error(); try { myResponse.headers.set("Origin", "http://mybank.com"); } catch(e) { console.log("Cannot pretend to be a bank!"); }
最佳實(shí)踐是在使用之前檢查 content type 是否正確,比如:
fetch(myRequest).then(function(response) { if(response.headers.get("content-type") === "application/json") { return response.json().then(function(json) { // process your JSON further }); } else { console.log("Oops, we haven't got JSON!"); } });
Guard
由于 Headers 可以在 request 請(qǐng)求中被發(fā)送或者在 response 請(qǐng)求中被接收,并且規(guī)定了哪些參數(shù)是可寫的,Headers 對(duì)象有一個(gè)特殊的 guard 屬性。這個(gè)屬性沒有暴露給 Web,但是它影響到哪些內(nèi)容可以在 Headers 對(duì)象中被操作。
可能的值如下:
none
:默認(rèn)的request
:從 request 中獲得的 headers(Request.headers
)只讀request-no-cors
:從不同域(Request.mode
no-cors
)的 request 中獲得的 headers 只讀response
:從 response 中獲得的 headers(Response.headers
)只讀immutable
:在 ServiceWorkers 中最常用的,所有的 headers 都只讀。
注意:你不可以添加或者修改一個(gè) guard 屬性是 request
的 Request Headers 的 Content-Length
屬性。同樣地,插入 Set-Cookie
屬性到一個(gè) response headers 是不允許的,因此 ServiceWorkers 是不能給合成的 Response 的 headers 添加一些 cookies。
Response 對(duì)象
如上述, Response
實(shí)例是在 fetch()
處理完promises之后返回的。
你會(huì)用到的最常見的response屬性有:
Response.status
— 整數(shù)(默認(rèn)值為200) 為response的狀態(tài)碼.Response.statusText
— 字符串(默認(rèn)值為"OK"),該值與HTTP狀態(tài)碼消息對(duì)應(yīng).Response.ok
— 如上所示, 該屬性是來檢查response的狀態(tài)是否在200-299(包括200,299)這個(gè)范圍內(nèi).該屬性返回一個(gè)Boolean
值.
它的實(shí)例也可用通過 JavaScript 來創(chuàng)建, 但只有在ServiceWorkers
中才真正有用,當(dāng)使用respondWith()
方法并提供了一個(gè)自定義的response來接受request時(shí):
var myBody = new Blob(); addEventListener('fetch', function(event) { event.respondWith(new Response(myBody, { headers: { "Content-Type" : "text/plain" } }); });
Response()
構(gòu)造方法接受兩個(gè)可選參數(shù)—response的數(shù)據(jù)體和一個(gè)初始化對(duì)象(與Request()
所接受的init參數(shù)類似.)
注意: 靜態(tài)方法error()
只是返回了一個(gè)錯(cuò)誤的response. 與此類似地, redirect()
只是返回了一個(gè)可以重定向至某URL的response. 這些也只與Service Workers才有關(guān)。
Body
不管是請(qǐng)求還是響應(yīng)都能夠包含body對(duì)象. body也可以是以下任意類型的實(shí)例.
ArrayBuffer
ArrayBufferView
(Uint8Array等)Blob
/File- string
URLSearchParams
- [
FormData
]("FormData 接口提供了一種表示表單數(shù)據(jù)的鍵值對(duì)的構(gòu)造方式,經(jīng)過它的數(shù)據(jù)可以使用 XMLHttpRequest.send() 方法送出,本接口和此方法都相當(dāng)簡(jiǎn)單直接。如果送出時(shí)的編碼類型被設(shè)為 "multipart/form-data",它會(huì)使用和表單一樣的格式。")
Body
類定義了以下方法 (這些方法都被 Request
和Response
所實(shí)現(xiàn))以獲取body內(nèi)容. 這些方法都會(huì)返回一個(gè)被解析后的Promise
對(duì)象和數(shù)據(jù).
arrayBuffer()
blob()
json()
- [
text()
]("Body混入的 text() 方法提供了一個(gè)可供讀取的"返回流", ——它返回一個(gè)包含USVString對(duì)象 (text)的Promise對(duì)象,返回結(jié)果的編碼為UTF-8。") formData()
比起XHR來,這些方法讓非文本化的數(shù)據(jù)使用起來更加簡(jiǎn)單。
請(qǐng)求體可以由傳入body參數(shù)來進(jìn)行設(shè)置:
var form = new FormData(document.getElementById('login-form')); fetch("/login", { method: "POST", body: form })
request和response(包括fetch()
方法)都會(huì)試著自動(dòng)設(shè)置Content-Type
。如果沒有設(shè)置Content-Type
值,發(fā)送的請(qǐng)求也會(huì)自動(dòng)設(shè)值。
特性檢測(cè)
Fetch API 的支持情況,可以通過檢測(cè)Headers
, Request
, Response
或 fetch()
是否在Window
或 Worker
域中。例如:
if(self.fetch) { // run my fetch request here } else { // do something with XMLHttpRequest? }
到此這篇關(guān)于JavaScript使用Fetch的方法詳解的文章就介紹到這了,更多相關(guān)JavaScript Fetch內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javascript window.confirm確認(rèn) 取消對(duì)話框?qū)崿F(xiàn)代碼小結(jié)
本文章講述的三種都是基于了javascript confirm提示確認(rèn)框的做法了,只是在不同的地方寫哦,有需要的同學(xué)可參考一下2012-10-10getElementByID、createElement、appendChild幾個(gè)DHTML元素
WEB標(biāo)準(zhǔn)下可以通過getElementById(), getElementsByName(), and getElementsByTagName()訪問2008-06-06Markdown+Bootstrap圖片自適應(yīng)屬性詳解
這篇文章主要為大家詳細(xì)介紹了Markdown+Bootstrap圖片自適應(yīng)屬性,感興趣的朋友可以參考一下2016-05-05mpvue微信小程序的接口請(qǐng)求fly全局?jǐn)r截代碼實(shí)例
這篇文章主要介紹了mpvue微信小程序的接口請(qǐng)求fly全局?jǐn)r截代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11取消Bootstrap的dropdown-menu點(diǎn)擊默認(rèn)關(guān)閉事件方法
今天小編就為大家分享一篇取消Bootstrap的dropdown-menu點(diǎn)擊默認(rèn)關(guān)閉事件方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-08-08Promise 鏈?zhǔn)秸{(diào)用原理精簡(jiǎn)示例
這篇文章主要為大家介紹了Promise 鏈?zhǔn)秸{(diào)用原理精簡(jiǎn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12