一、什么是Fetch ?
1.Fetch本質(zhì)上是一種標(biāo)準(zhǔn),該標(biāo)準(zhǔn)定義了請(qǐng)求、響應(yīng)和綁定的流程。
2.Fetch標(biāo)準(zhǔn)還定義了Fetch () JavaScript API。
3.可用于前后端,數(shù)據(jù)交互。
4.fetch返回的是promise對(duì)象,比XMLHttpRequest的實(shí)現(xiàn)更簡(jiǎn)潔,fetch 使用起來更簡(jiǎn)潔 ,完成工作所需的實(shí)際代碼量也更少
5.fetch 可自定義是否攜帶Cookie。
6.fetch不像axios需要安裝使用,fetch可以直接使用。
二、如何使用Fetch
Fetch API 提供了一種全局fetch()方法,該方法位于 WorkerOrGlobalScope 這一個(gè) mixin 中 方法用于發(fā)起獲取資源的請(qǐng)求。它返回一個(gè) promise,這個(gè) promise 會(huì)在請(qǐng)求響應(yīng)后被 resolve,并傳回 Response 對(duì)象。
fetch(input?: Request | string, init?: RequestInit): Promise<Response>
fetch(url, options).then(function(response) {
// 處理 HTTP 響應(yīng)
}, function(error) {
// 處理網(wǎng)絡(luò)錯(cuò)誤
})
fetch() 參數(shù)
fetch方法可以接收兩個(gè)參數(shù)input和options。
- input 參數(shù)可以是字符串,包含要獲取資源的 URL。也可以是一個(gè) Request 對(duì)象。
- options 是一個(gè)可選參數(shù)。一個(gè)配置項(xiàng)對(duì)象,包括所有對(duì)請(qǐng)求的設(shè)置??蛇x的參數(shù)有:
method: 請(qǐng)求使用的方法,如 GET、POST、DELETE、PUT等。
headers: 請(qǐng)求的頭信息,包含與請(qǐng)求關(guān)聯(lián)的Headers對(duì)象。
body: 請(qǐng)求的 body 信息。注意 GET 或 HEAD 方法的請(qǐng)求不能包含 body 信息
mode: 請(qǐng)求的模式,如 cors、 no-cors 或者 same-origin。
credentials: 請(qǐng)求的 credentials,如 omit、same-origin 或者 include。為了在當(dāng)前域名內(nèi)自動(dòng)發(fā)送 cookie , 必須提供這個(gè)選項(xiàng)。
三、常用的fetch請(qǐng)求
html
fetch('/index/fetchHtml')
.then(res => {
return res.text() // 定義返回格式。
}).then(res => {
document.body.innerHTML += res
})
.catch((err) => {
})
JSON
fetch('請(qǐng)求路徑')
.then((res) => {
return res.json()
})
.then(res => {
console.log(res)
})
.catch((err => {
}))
POST JSON
fetch('請(qǐng)求路徑',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: '張麻子',
age: '26',
})
})
.then((res) => {
return res.json()
})
.then(res => {
console.log(res)
})
.catch((err => {
}))
4、fetch注意事項(xiàng)
1. 錯(cuò)誤處理
fetch只有在網(wǎng)絡(luò)錯(cuò)誤的情況,返回的promise會(huì)被reject。成功的 fetch() 檢查不僅要包括 promise 被 resolve,還要包括 Response.ok 屬性為 true。HTTP 404 狀態(tài)并不被認(rèn)為是網(wǎng)絡(luò)錯(cuò)誤,所以Promise的狀態(tài)為resolve。
2. credentials 設(shè)置
fetch可以通過credentials自己控制發(fā)送請(qǐng)求時(shí)是否帶上cookie。credentials可設(shè)置為include、same-origin、omit。include為了讓瀏覽器發(fā)送包含憑據(jù)的請(qǐng)求(即使是跨域源)。如果你只想在請(qǐng)求URL與調(diào)用腳本位于同一起源處時(shí)發(fā)送憑據(jù),請(qǐng)?zhí)砑觕redentials: 'same-origin'。要改為確保瀏覽器不在請(qǐng)求中包含憑據(jù),請(qǐng)使用credentials: 'omit'。
5.fetch簡(jiǎn)單封裝
1.和src同級(jí)新建一個(gè)api(名字可以隨意起)的文件夾,在文件夾里面新建一個(gè)request.js (名字可以隨意起)文件內(nèi)容如下:
export default async(url = '', data = {}, type = 'GET') => {
const baseUrl = "https://api.it120.cc/small4" // 基礎(chǔ)路徑
type = type.toUpperCase(); // 請(qǐng)求方式小寫轉(zhuǎn)換成大寫
url = baseUrl + url; // 請(qǐng)求地址的拼接
if (type == 'GET') {
let dataStr = ''; //數(shù)據(jù)拼接字符串
Object.keys(data).forEach(key => {
dataStr += key + '=' + data[key] + '&';
})
if (dataStr !== '') {
dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
url = url + '?' + dataStr;
}
}
let requestConfig = {
credentials: 'same-origin',
method: type,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
mode: "cors", // 用來決定是否允許跨域請(qǐng)求 值有 三個(gè) same-origin,no-cors(默認(rèn))以及 cores;
cache: "force-cache" // 是否緩存請(qǐng)求資源 可選值有 default 、 no-store 、 reload 、 no-cache 、 force-cache 或者 only-if-cached 。
}
if (type == 'POST') {
Object.defineProperty(requestConfig, 'body', {
value: JSON.stringify(data)
})
}
try {
const response = await fetch(url, requestConfig);
const responseJson = await response.json();
return responseJson
} catch (error) {
throw new Error(error)
}
}
6.封裝接口
import api from '../request.js';
下面是簡(jiǎn)寫的形式
// getXXX 自定義的接口名字
export const getXXX = (params) => api(`/apigb/v1/component`, params)
export const postXXX = (params) => api.post(`/apigb/v1/component/update-info`, params,'post')