原文鏈接:https://segmentfault.com/a/1190000011433064
function obj2String(obj, arr = [], idx = 0) {
for (let item in obj) {
arr[idx++] = [item, obj[item]]
}
console.log(arr);//構(gòu)造[["a":1]["b":2]["c":3]]這樣的結(jié)構(gòu)輸入U(xiǎn)RLSearchParams。
return new URLSearchParams(arr).toString();
}
var bddd = obj2String({
a:1,
b:2,
d:[22]
})
console.log(bddd);
fetch和XMLHttpRequest
如果看網(wǎng)上的fetch教程,會(huì)首先對比XMLHttpRequest和fetch的優(yōu)劣,然后引出一堆看了很快會(huì)忘記的內(nèi)容(本人記性不好)。因此,我寫一篇關(guān)于fetch的文章,為了自己看著方便,畢竟工作中用到的也就是一些很基礎(chǔ)的點(diǎn)而已。
fetch,說白了,就是XMLHttpRequest的一種替代方案。如果有人問你,除了Ajax獲取后臺(tái)數(shù)據(jù)之外,還有沒有其他的替代方案?
這是你就可以回答,除了XMLHttpRequest對象來獲取后臺(tái)的數(shù)據(jù)之外,還可以使用一種更優(yōu)的解決方案fetch。
如何獲取fetch
到現(xiàn)在為止,fetch的支持性還不是很好,但是在谷歌瀏覽器中已經(jīng)支持了fetch。fetch掛在在BOM中,可以直接在谷歌瀏覽器中使用。
查看fetch的支持情況:fetch的支持情況
當(dāng)然,如果不支持fetch也沒有問題,可以使用第三方的ployfill來實(shí)現(xiàn)只會(huì)fetch:whatwg-fetch
fetch的helloworld
下面我們來寫第一個(gè)fetch獲取后端數(shù)據(jù)的例子:
// 通過fetch獲取百度的錯(cuò)誤提示頁面
fetch('https://www.baidu.com/search/error.html') // 返回一個(gè)Promise對象
.then((res)=>{
return res.text() // res.text()是一個(gè)Promise對象
})
.then((res)=>{
console.log(res) // res是最終的結(jié)果
})
是不是很簡單?可能難的地方就是Promise的寫法,這個(gè)可以看阮一峰老師的ES6教程來學(xué)習(xí)。
說明一點(diǎn),下面演示的GET請求或POST請求,都是采用百度中查詢到的一些接口,可能傳遞的有些參數(shù)這個(gè)接口并不會(huì)解析,但不會(huì)影響這個(gè)接口的使用。
GET請求
GET請求初步
完成了helloworld,這個(gè)時(shí)候就要來認(rèn)識(shí)一下GET請求如何處理了。
上面的helloworld中這是使用了第一個(gè)參數(shù),其實(shí)fetch還可以提供第二個(gè)參數(shù),就是用來傳遞一些初始化的信息。
這里如果要特別指明是GET請求,就要寫成下面的形式:
// 通過fetch獲取百度的錯(cuò)誤提示頁面
fetch('https://www.baidu.com/search/error.html', {
method: 'GET'
})
.then((res)=>{
return res.text()
})
.then((res)=>{
console.log(res)
})
GET請求的參數(shù)傳遞
GET請求中如果需要傳遞參數(shù)怎么辦?這個(gè)時(shí)候,只能把參數(shù)寫在URL上來進(jìn)行傳遞了。
// 通過fetch獲取百度的錯(cuò)誤提示頁面
fetch('https://www.baidu.com/search/error.html?a=1&b=2', { // 在URL中寫上傳遞的參數(shù)
method: 'GET'
})
.then((res)=>{
return res.text()
})
.then((res)=>{
console.log(res)
})
POST請求
POST請求初步
與GET請求類似,POST請求的指定也是在fetch的第二個(gè)參數(shù)中:
// 通過fetch獲取百度的錯(cuò)誤提示頁面
fetch('https://www.baidu.com/search/error.html', {
method: 'POST' // 指定是POST請求
})
.then((res)=>{
return res.text()
})
.then((res)=>{
console.log(res)
})
POST請求參數(shù)的傳遞
眾所周知,POST請求的參數(shù),一定不能放在URL中,這樣做的目的是防止信息泄露。
// 通過fetch獲取百度的錯(cuò)誤提示頁面
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)
})
其實(shí)除了對象URLSearchParams外,還有幾個(gè)其他的對象,可以參照:常用的幾個(gè)對象來學(xué)習(xí)使用。
設(shè)置請求的頭信息
在POST提交的過程中,一般是表單提交,可是,經(jīng)過查詢,發(fā)現(xiàn)默認(rèn)的提交方式是:Content-Type:text/plain;charset=UTF-8,這個(gè)顯然是不合理的。下面咱們學(xué)習(xí)一下,指定頭信息:
// 通過fetch獲取百度的錯(cuò)誤提示頁面
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)
})
這個(gè)時(shí)候,在谷歌瀏覽器的Network中查詢,會(huì)發(fā)現(xiàn),請求方式已經(jīng)變成了content-type:application/x-www-form-urlencoded。
通過接口得到JSON數(shù)據(jù)
上面所有的例子中都是返回一個(gè)文本,那么除了文本,有沒有其他的數(shù)據(jù)類型呢?肯定是有的,具體查詢地址:Body的類型
由于最常用的是JSON數(shù)據(jù),那么下面就簡單演示一下獲取JSON數(shù)據(jù)的方式:
// 通過fetch獲取百度的錯(cuò)誤提示頁面
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中寫上傳遞的參數(shù)
method: 'GET',
headers: new Headers({
'Accept': 'application/json' // 通過頭指定,獲取的數(shù)據(jù)類型是JSON
})
})
.then((res)=>{
return res.json() // 返回一個(gè)Promise,可以解析成JSON
})
.then((res)=>{
console.log(res) // 獲取JSON數(shù)據(jù)
})
強(qiáng)制帶Cookie
默認(rèn)情況下, fetch 不會(huì)從服務(wù)端發(fā)送或接收任何 cookies, 如果站點(diǎn)依賴于維護(hù)一個(gè)用戶會(huì)話,則導(dǎo)致未經(jīng)認(rèn)證的請求(要發(fā)送 cookies,必須發(fā)送憑據(jù)頭).
// 通過fetch獲取百度的錯(cuò)誤提示頁面
fetch('https://www.baidu.com/search/error.html', {
method: 'GET',
credentials: 'include' // 強(qiáng)制加入憑據(jù)頭
})
.then((res)=>{
return res.text()
})
.then((res)=>{
console.log(res)
})
簡單封裝一下fetch
最后了,介紹了一大堆內(nèi)容,有沒有發(fā)現(xiàn),在GET和POST傳遞參數(shù)的方式不同呢?下面咱們就來封裝一個(gè)簡單的fetch,來實(shí)現(xiàn)GET請求和POST請求參數(shù)的統(tǒng)一。
/**
* 將對象轉(zhuǎn)成 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 請求參數(shù)
* @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 請求參數(shù)
*/
function GET(url, options) {
return commonFetcdh(url, options, 'GET')
}
/**
* POST請求
* @param url 請求地址
* @param options 請求參數(shù)
*/
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})