JavaScript使用Fetch的方法詳解
Fetch API 提供了一個 JavaScript接口,用于訪問和操縱HTTP管道的部分,例如請求和響應(yīng)。它還提供了一個全局 fetch()
方法,該方法提供了一種簡單,合理的方式來跨網(wǎng)絡(luò)異步獲取資源。
這種功能以前是使用 XMLHttpRequest
實現(xiàn)的。Fetch提供了一個更好的替代方法,可以很容易地被其他技術(shù)使用,例如 Service Workers
。Fetch還提供了單個邏輯位置來定義其他HTTP相關(guān)概念,例如CORS和HTTP的擴展。
請注意,fetch
規(guī)范與jQuery.ajax()
主要有兩種方式的不同,牢記:
- 當接收到一個代表錯誤的 HTTP 狀態(tài)碼時,從
fetch()
返回的 Promise 不會被標記為 reject, 即使該 HTTP 響應(yīng)的狀態(tài)碼是 404 或 500。相反,它會將 Promise 狀態(tài)標記為 resolve (但是會將 resolve 的返回值的ok
屬性設(shè)置為 false ),僅當網(wǎng)絡(luò)故障時或請求被阻止時,才會標記為 reject。 - 默認情況下,
fetch
不會從服務(wù)端發(fā)送或接收任何 cookies, 如果站點依賴于用戶 session,則會導致未經(jīng)認證的請求(要發(fā)送 cookies,必須設(shè)置 credentials 選項)。自從2017年8月25日后,默認的credentials政策變更為same-origin
Firefox也在61.0b13中改變默認值
進行 fetch 請求
一個基本的 fetch請求設(shè)置起來很簡單??纯聪旅娴拇a:
fetch('http://example.com/movies.json') .then(function(response) { return response.json(); }) .then(function(myJson) { console.log(myJson); });
這里我們通過網(wǎng)絡(luò)獲取一個JSON文件并將其打印到控制臺。最簡單的用法是只提供一個參數(shù)用來指明想fetch()
到的資源路徑,然后返回一個包含響應(yīng)結(jié)果的promise(一個 Response
對象)。
當然它只是一個 HTTP 響應(yīng),而不是真的JSON。為了獲取JSON的內(nèi)容,我們需要使用 json()
方法(在Body
mixin 中定義,被 Request
和 Response
對象實現(xiàn))。
注意:Body mixin 還有其他相似的方法,用于獲取其他類型的內(nèi)容。參考 Body。
最好使用符合內(nèi)容安全策略 (CSP)的鏈接而不是使用直接指向資源地址的方式來進行Fetch的請求。
支持的請求參數(shù)
fetch()
接受第二個可選參數(shù),一個可以控制不同配置的 init
對象:
參考 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ù)的請求
為了讓瀏覽器發(fā)送包含憑據(jù)的請求(即使是跨域源),要將credentials: 'include'
添加到傳遞給 fetch()
方法的init
對象。
fetch('https://example.com', { credentials: 'include' })
如果你只想在請求URL與調(diào)用腳本位于同一起源處時發(fā)送憑據(jù),請?zhí)砑?code>credentials: 'same-origin'。
// The calling script is on the origin 'https://example.com' fetch('https://example.com', { credentials: 'same-origin' })
要改為確保瀏覽器不在請求中包含憑據(jù),請使用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));
上傳多個文件
可以通過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));
檢測請求是否成功
如果遇到網(wǎng)絡(luò)故障,fetch()
promise 將會 reject,帶上一個 TypeError
對象。雖然這個情況經(jīng)常是遇到了權(quán)限問題或類似問題——比如 404 不是一個網(wǎng)絡(luò)故障。想要精確的判斷 fetch()
是否成功,需要包含 promise resolved 的情況,此時再判斷 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); });
自定義請求對象
除了傳給 fetch()
一個資源的地址,你還可以通過使用 Request()
構(gòu)造函數(shù)來創(chuàng)建一個 request 對象,然后再作為參數(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ù)。你甚至可以傳入一個已存在的 request 對象來創(chuàng)造一個拷貝:
var anotherRequest = new Request(myRequest,myInit);
這個很有用,因為 request 和 response bodies 只能被使用一次(譯者注:這里的意思是因為設(shè)計成了 stream 的方式,所以它們只能被讀取一次)。創(chuàng)建一個拷貝就可以再次使用 request/response 了,當然也可以使用不同的 init
參數(shù)。
注意:clone()
方法也可以用于創(chuàng)建一個拷貝。它在語義上有一點不同于其他拷貝的方法。其他方法(比如拷貝一個 response)中,如果 request 的 body 已經(jīng)被讀取過,那么將執(zhí)行失敗,然而 clone()
則不會失敗。
Headers
使用 Headers
的接口,你可以通過 Headers()
構(gòu)造函數(shù)來創(chuàng)建一個你自己的 headers 對象。一個 headers 對象是一個簡單的多名值對:
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");
也可以傳一個多維數(shù)組或者對象字面量:
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。
如果使用了一個不合法的HTTP Header屬性名,那么Headers的方法通常都拋出 TypeError 異常。如果不小心寫入了一個不可寫的屬性,也會拋出一個 TypeError 異常。除此以外的情況,失敗了并不拋出異常。例如:
var myResponse = Response.error(); try { myResponse.headers.set("Origin", "http://mybank.com"); } catch(e) { console.log("Cannot pretend to be a bank!"); }
最佳實踐是在使用之前檢查 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 請求中被發(fā)送或者在 response 請求中被接收,并且規(guī)定了哪些參數(shù)是可寫的,Headers 對象有一個特殊的 guard 屬性。這個屬性沒有暴露給 Web,但是它影響到哪些內(nèi)容可以在 Headers 對象中被操作。
可能的值如下:
none
:默認的request
:從 request 中獲得的 headers(Request.headers
)只讀request-no-cors
:從不同域(Request.mode
no-cors
)的 request 中獲得的 headers 只讀response
:從 response 中獲得的 headers(Response.headers
)只讀immutable
:在 ServiceWorkers 中最常用的,所有的 headers 都只讀。
注意:你不可以添加或者修改一個 guard 屬性是 request
的 Request Headers 的 Content-Length
屬性。同樣地,插入 Set-Cookie
屬性到一個 response headers 是不允許的,因此 ServiceWorkers 是不能給合成的 Response 的 headers 添加一些 cookies。
Response 對象
如上述, Response
實例是在 fetch()
處理完promises之后返回的。
你會用到的最常見的response屬性有:
Response.status
— 整數(shù)(默認值為200) 為response的狀態(tài)碼.Response.statusText
— 字符串(默認值為"OK"),該值與HTTP狀態(tài)碼消息對應(yīng).Response.ok
— 如上所示, 該屬性是來檢查response的狀態(tài)是否在200-299(包括200,299)這個范圍內(nèi).該屬性返回一個Boolean
值.
它的實例也可用通過 JavaScript 來創(chuàng)建, 但只有在ServiceWorkers
中才真正有用,當使用respondWith()
方法并提供了一個自定義的response來接受request時:
var myBody = new Blob(); addEventListener('fetch', function(event) { event.respondWith(new Response(myBody, { headers: { "Content-Type" : "text/plain" } }); });
Response()
構(gòu)造方法接受兩個可選參數(shù)—response的數(shù)據(jù)體和一個初始化對象(與Request()
所接受的init參數(shù)類似.)
注意: 靜態(tài)方法error()
只是返回了一個錯誤的response. 與此類似地, redirect()
只是返回了一個可以重定向至某URL的response. 這些也只與Service Workers才有關(guān)。
Body
不管是請求還是響應(yīng)都能夠包含body對象. body也可以是以下任意類型的實例.
ArrayBuffer
ArrayBufferView
(Uint8Array等)Blob
/File- string
URLSearchParams
- [
FormData
]("FormData 接口提供了一種表示表單數(shù)據(jù)的鍵值對的構(gòu)造方式,經(jīng)過它的數(shù)據(jù)可以使用 XMLHttpRequest.send() 方法送出,本接口和此方法都相當簡單直接。如果送出時的編碼類型被設(shè)為 "multipart/form-data",它會使用和表單一樣的格式。")
Body
類定義了以下方法 (這些方法都被 Request
和Response
所實現(xiàn))以獲取body內(nèi)容. 這些方法都會返回一個被解析后的Promise
對象和數(shù)據(jù).
arrayBuffer()
blob()
json()
- [
text()
]("Body混入的 text() 方法提供了一個可供讀取的"返回流", ——它返回一個包含USVString對象 (text)的Promise對象,返回結(jié)果的編碼為UTF-8。") formData()
比起XHR來,這些方法讓非文本化的數(shù)據(jù)使用起來更加簡單。
請求體可以由傳入body參數(shù)來進行設(shè)置:
var form = new FormData(document.getElementById('login-form')); fetch("/login", { method: "POST", body: form })
request和response(包括fetch()
方法)都會試著自動設(shè)置Content-Type
。如果沒有設(shè)置Content-Type
值,發(fā)送的請求也會自動設(shè)值。
特性檢測
Fetch API 的支持情況,可以通過檢測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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javascript window.confirm確認 取消對話框?qū)崿F(xiàn)代碼小結(jié)
本文章講述的三種都是基于了javascript confirm提示確認框的做法了,只是在不同的地方寫哦,有需要的同學可參考一下2012-10-10getElementByID、createElement、appendChild幾個DHTML元素
WEB標準下可以通過getElementById(), getElementsByName(), and getElementsByTagName()訪問2008-06-06Markdown+Bootstrap圖片自適應(yīng)屬性詳解
這篇文章主要為大家詳細介紹了Markdown+Bootstrap圖片自適應(yīng)屬性,感興趣的朋友可以參考一下2016-05-05取消Bootstrap的dropdown-menu點擊默認關(guān)閉事件方法
今天小編就為大家分享一篇取消Bootstrap的dropdown-menu點擊默認關(guān)閉事件方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08