Fetch和XMLHttpRequest
如果看網上的fetch教程,會首先對比XMLHttpRequest和fetch的優劣,然後引出一堆看了很快會忘記的內容(本人記性不好)。因此,我寫一篇關於fetch的文章,爲了自己看着方便,畢竟工作中用到的也就是一些很基礎的點而已。
fetch,說白了,就是XMLHttpRequest的一種替代方案。如果有人問你,除了Ajax獲取後臺數據之外,還有沒有其他的替代方案?
這是你就可以回答,除了XMLHttpRequest對象來獲取後臺的數據之外,還可以使用一種更優的解決方案fetch。
如何獲取fetch
到現在爲止,fetch的支持性還不是很好,但是在谷歌瀏覽器中已經支持了fetch。fetch掛在在BOM中,可以直接在谷歌瀏覽器中使用。
查看fetch的支持情況:fetch的支持情況
當然,如果不支持fetch也沒有問題,可以使用第三方的ployfill來實現只會fetch:whatwg-fetch
fetch的helloworld
下面我們來寫第一個fetch獲取後端數據的例子:
// 通過fetch獲取百度的錯誤提示頁面
fetch('https://www.baidu.com/search/error.html') // 返回一個Promise對象
.then((res)=>{
return res.text() // res.text()是一個Promise對象
})
.then((res)=>{
console.log(res) // res是最終的結果
})
是不是很簡單?可能難的地方就是Promise的寫法,這個可以看阮一峯老師的ES6教程來學習。
說明一點,下面演示的GET請求或POST請求,都是採用百度中查詢到的一些接口,可能傳遞的有些參數這個接口並不會解析,但不會影響這個接口的使用。
GET請求
GET請求初步
完成了helloworld,這個時候就要來認識一下GET請求如何處理了。
上面的helloworld中這是使用了第一個參數,其實fetch還可以提供第二個參數,就是用來傳遞一些初始化的信息。
這裏如果要特別指明是GET請求,就要寫成下面的形式:
// 通過fetch獲取百度的錯誤提示頁面
fetch('https://www.baidu.com/search/error.html', {
method: 'GET'
})
.then((res)=>{
return res.text()
})
.then((res)=>{
console.log(res)
})
GET請求的參數傳遞
GET請求中如果需要傳遞參數怎麼辦?這個時候,只能把參數寫在URL上來進行傳遞了。
// 通過fetch獲取百度的錯誤提示頁面
fetch('https://www.baidu.com/search/error.html?a=1&b=2', { // 在URL中寫上傳遞的參數
method: 'GET'
})
.then((res)=>{
return res.text()
})
.then((res)=>{
console.log(res)
})
POST請求
POST請求初步
與GET請求類似,POST請求的指定也是在fetch的第二個參數中:
// 通過fetch獲取百度的錯誤提示頁面
fetch('https://www.baidu.com/search/error.html', {
method: 'POST' // 指定是POST請求
})
.then((res)=>{
return res.text()
})
.then((res)=>{
console.log(res)
})
POST請求參數的傳遞
衆所周知,POST請求的參數,一定不能放在URL中,這樣做的目的是防止信息泄露。
// 通過fetch獲取百度的錯誤提示頁面
fetch('https://www.baidu.com/search/error.html', {
method: 'POST',
body: new URLSearchParams([["foo", 1],["bar", 2]]).toString() // 這裏是請求對象
})
.then((res)=>{
return res.text()
})
.then((res)=>{
console.log(res)
})
其實除了對象URLSearchParams
外,還有幾個其他的對象,可以參照:常用的幾個對象來學習使用。
設置請求的頭信息
在POST提交的過程中,一般是表單提交,可是,經過查詢,發現默認的提交方式是:Content-Type:text/plain;charset=UTF-8
,這個顯然是不合理的。下面咱們學習一下,指定頭信息:
// 通過fetch獲取百度的錯誤提示頁面
fetch('https://www.baidu.com/search/error.html', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式爲表單提交
}),
body: new URLSearchParams([["foo", 1],["bar", 2]]).toString()
})
.then((res)=>{
return res.text()
})
.then((res)=>{
console.log(res)
})
這個時候,在谷歌瀏覽器的Network中查詢,會發現,請求方式已經變成了content-type:application/x-www-form-urlencoded
。
通過接口得到JSON數據
上面所有的例子中都是返回一個文本,那麼除了文本,有沒有其他的數據類型呢?肯定是有的,具體查詢地址:Body的類型
由於最常用的是JSON數據,那麼下面就簡單演示一下獲取JSON數據的方式:
// 通過fetch獲取百度的錯誤提示頁面
fetch('https://www.baidu.com/rec?platform=wise&ms=1&rset=rcmd&word=123&qid=11327900426705455986&rq=123&from=844b&baiduid=A1D0B88941B30028C375C79CE5AC2E5E%3AFG%3D1&tn=&clientWidth=375&t=1506826017369&r=8255', { // 在URL中寫上傳遞的參數
method: 'GET',
headers: new Headers({
'Accept': 'application/json' // 通過頭指定,獲取的數據類型是JSON
})
})
.then((res)=>{
return res.json() // 返回一個Promise,可以解析成JSON
})
.then((res)=>{
console.log(res) // 獲取JSON數據
})
強制帶Cookie
默認情況下, fetch 不會從服務端發送或接收任何 cookies, 如果站點依賴於維護一個用戶會話,則導致未經認證的請求(要發送 cookies,必須發送憑據頭).
// 通過fetch獲取百度的錯誤提示頁面
fetch('https://www.baidu.com/search/error.html', {
method: 'GET',
credentials: 'include' // 強制加入憑據頭
})
.then((res)=>{
return res.text()
})
.then((res)=>{
console.log(res)
})
簡單封裝一下fetch
最後了,介紹了一大堆內容,有沒有發現,在GET和POST傳遞參數的方式不同呢?下面咱們就來封裝一個簡單的fetch,來實現GET請求和POST請求參數的統一。
/**
* 將對象轉成 a=1&b=2的形式
* @param obj 對象
*/
function obj2String(obj, arr = [], idx = 0) {
for (let item in obj) {
arr[idx++] = [item, obj[item]]
}
return new URLSearchParams(arr).toString()
}
/**
* 真正的請求
* @param url 請求地址
* @param options 請求參數
* @param method 請求方式
*/
function commonFetcdh(url, options, method = 'GET') {
const searchStr = obj2String(options)
let initObj = {}
if (method === 'GET') { // 如果是GET請求,拼接url
url += '?' + searchStr
initObj = {
method: method,
credentials: 'include'
}
} else {
initObj = {
method: method,
credentials: 'include',
headers: new Headers({
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
}),
body: searchStr
}
}
fetch(url, initObj).then((res) => {
return res.json()
}).then((res) => {
return res
})
}
/**
* GET請求
* @param url 請求地址
* @param options 請求參數
*/
function GET(url, options) {
return commonFetcdh(url, options, 'GET')
}
/**
* POST請求
* @param url 請求地址
* @param options 請求參數
*/
function POST(url, options) {
return commonFetcdh(url, options, 'POST')
}
GET('https://www.baidu.com/search/error.html', {a:1,b:2})
POST('https://www.baidu.com/search/error.html', {a:1,b:2})