除了XMLHttpRequest對象來獲取后台的數據之外,還可以使用一種更優的解決方案——fetch
㈠fetch示例
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是最終的結果 })
㈡GET請求
⑴GET請求初步
fetch可以提供第二個參數,就是用來傳遞一些初始化的信息。
// 通過fetch獲取百度的錯誤提示頁面 fetch('https://www.baidu.com/search/error.html', { method: 'GET' }) .then((res)=>{ return res.text() }) .then((res)=>{ console.log(res) })
⑵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請求的指定也是在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) })
⑶設置請求的頭信息
在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數據的方式:
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) })
