最新的Web API接口中提供了一個(gè)全局fetch方法,從而以一種更為簡(jiǎn)單、合理的方式來(lái)支持跨網(wǎng)絡(luò)異步獲取資源。

這種功能以前是使用 XMLHttpRequest實(shí)現(xiàn)的。Fetch提供了一個(gè)更好的替代方法,可以很容易地被其他技術(shù)使用,例如 Service Workers。Fetch還提供了單個(gè)邏輯位置來(lái)定義其他HTTP相關(guān)概念,例如CORS和HTTP的擴(kuò)展。
請(qǐng)注意,fetch規(guī)范與jQuery.ajax()主要有兩種方式的不同:
一個(gè)基本的 fetch請(qǐng)求設(shè)置起來(lái)很簡(jiǎn)單。看看下面的代碼:
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});這里我們通過(guò)網(wǎng)絡(luò)獲取一個(gè)JSON文件并將其打印到控制臺(tái)。最簡(jiǎn)單的用法是只提供一個(gè)參數(shù)用來(lái)指明想fetch()到的資源路徑,然后返回一個(gè)包含響應(yīng)結(jié)果的promise(一個(gè) Response 對(duì)象)。
fetch() 接受第二個(gè)可選參數(shù),一個(gè)可以控制不同配置的 init 對(duì)象:
參考 fetch(),查看所有可選的配置和更多描述。
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)求(即使是跨域源),要將credentials: 'include'添加到傳遞給 fetch()方法的init對(duì)象。
fetch('https://example.com', {
credentials: 'include'
})如果你只想在請(qǐng)求URL與調(diào)用腳本位于同一起源處時(shí)發(fā)送憑據(jù),請(qǐng)?zhí)砑觕redentials: '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'
})
下面的示例片斷展示了使用fetch()方法以POST方式發(fā)送 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));
在最新瀏覽器API編程中,你可以使用一個(gè)HTML <input type="file" /> 輸入元素,并結(jié)合FormData() 函數(shù)和fetch()函數(shù)實(shí)現(xiàn)上傳文件:
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));
如果遇到網(wǎng)絡(luò)故障,fetch() (其實(shí)是一個(gè)promise對(duì)象)將會(huì)Reject,帶上一個(gè) TypeError 對(duì)象。雖然這個(gè)情況經(jīng)常是遇到了權(quán)限問(wèn)題或類(lèi)似問(wèn)題——比如 404 不是一個(gè)網(wǎng)絡(luò)故障。想要精確的判斷 fetch() 是否成功,需要包含 promise解析的情況,此時(shí)再判斷 Response.ok 是不是為 true。類(lèi)似以下代碼:
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() 一個(gè)資源的地址,你還可以通過(guò)使用 Request() 構(gòu)造函數(shù)來(lái)創(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ì)象來(lái)創(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ù)。
要在不支持的瀏覽器中使用Fetch,可以使用Fetch Polypill(https://github.com/github/fetch)。
上面示例中使用了 fetch API。它是替代 XMLHttpRequest 用來(lái)發(fā)送網(wǎng)絡(luò)請(qǐng)求的非常新的 API。由于目前大多數(shù)瀏覽器原生還不支持它,React開(kāi)發(fā)中建議你使用 cross_fetch 庫(kù)(https://github.com/lquixada/cross-fetch):
// 每次使用 `fetch` 前都這樣調(diào)用一下
import fetch from 'cross_fetch'在底層,它在瀏覽器端使用 whatwg-fetch polyfill,在服務(wù)器端使用 node-fetch,所以如果當(dāng)你把應(yīng)用改成 同構(gòu) 時(shí),并不需要改變 API 請(qǐng)求。
注意,fetch polyfill 假設(shè)你已經(jīng)使用了 Promise 的 polyfill。確保你使用 Promise polyfill 的一個(gè)最簡(jiǎn)單的辦法是在所有應(yīng)用代碼前啟用 Babel 的 ES6 polyfill:
// 在應(yīng)用中其它任何代碼執(zhí)行前調(diào)用一次
import 'babel-polyfill'
import fetch from 'cross-fetch'
export const REQUEST_POSTS = 'REQUEST_POSTS'
function requestPosts(subreddit) {
return {
type: REQUEST_POSTS,
subreddit
}
}
export const RECEIVE_POSTS = 'RECEIVE_POSTS'
function receivePosts(subreddit, json) {
return {
type: RECEIVE_POSTS,
subreddit,
posts: json.data.children.map(child => child.data),
receivedAt: Date.now()
}
}
export const INVALIDATE_SUBREDDIT = ‘INVALIDATE_SUBREDDIT’
export function invalidateSubreddit(subreddit) {
return {
type: INVALIDATE_SUBREDDIT,
subreddit
}
}
// 來(lái)看一下我們寫(xiě)的第一個(gè) thunk action 創(chuàng)建函數(shù)!
// 雖然內(nèi)部操作不同,你可以像其它 action 創(chuàng)建函數(shù) 一樣使用它:
// store.dispatch(fetchPosts('reactjs'))
export function fetchPosts(subreddit) {
// Thunk middleware 知道如何處理函數(shù)。
// 這里把 dispatch 方法通過(guò)參數(shù)的形式傳給函數(shù),
// 以此來(lái)讓它自己也能 dispatch action。
return function (dispatch) {
// 首次 dispatch:更新應(yīng)用的 state 來(lái)通知
// API 請(qǐng)求發(fā)起了。
dispatch(requestPosts(subreddit))
// thunk middleware 調(diào)用的函數(shù)可以有返回值,
// 它會(huì)被當(dāng)作 dispatch 方法的返回值傳遞。
// 這個(gè)案例中,我們返回一個(gè)等待處理的 promise。
// 這并不是 redux middleware 所必須的,但這對(duì)于我們而言很方便。
return fetch(`http://www.subreddit.com/r/${subreddit}.json`)
.then(
response => response.json(),
// 不要使用 catch,因?yàn)闀?huì)捕獲
// 在 dispatch 和渲染中出現(xiàn)的任何錯(cuò)誤,
// 導(dǎo)致 'Unexpected batch number' 錯(cuò)誤。
// https://github.com/facebook/react/issues/6895
error => console.log('An error occurred.', error)
)
.then(json =>
// 可以多次 dispatch!
// 這里,使用 API 請(qǐng)求結(jié)果來(lái)更新應(yīng)用的 state。
dispatch(receivePosts(subreddit, json))
)}
}
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線(xiàn),公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性?xún)r(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專(zhuān)為企業(yè)上云打造定制,能夠滿(mǎn)足用戶(hù)豐富、多元化的應(yīng)用場(chǎng)景需求。
網(wǎng)頁(yè)題目:React開(kāi)發(fā)中使用fetch進(jìn)行異步請(qǐng)求-創(chuàng)新互聯(lián)
轉(zhuǎn)載來(lái)于:http://chinadenli.net/article26/digscg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供小程序開(kāi)發(fā)、品牌網(wǎng)站設(shè)計(jì)、關(guān)鍵詞優(yōu)化、網(wǎng)頁(yè)設(shè)計(jì)公司、品牌網(wǎng)站制作、做網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容