JavaScript fetch接口

JavaScript fetch接口

若是看網上的fetch教程,會首先對比XMLHttpRequest和fetch的優劣,而後引出一堆看了很快會忘記的內容(本人記性很差)。所以,我寫一篇關於fetch的文章,爲了本身看着方便,畢竟工做中用到的也就是一些很基礎的點而已。html

fetch,說白了,就是XMLHttpRequest的一種替代方案。若是有人問你,除了Ajax獲取後臺數據以外,還有沒有其餘的替代方案?json

這是你就能夠回答,除了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請求初步

完成了helloworld,這個時候就要來認識一下GET請求如何處理了。瀏覽器

上面的helloworld中這是使用了第一個參數,其實fetch還能夠提供第二個參數,就是用來傳遞一些初始化的信息。cookie

這裏若是要特別指明是GET請求,就要寫成下面的形式:app

// 經過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請求

與GET請求相似,POST請求的指定也是在fetch的第二個參數中: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中,這樣作的目的是防止信息泄露。ui

// 經過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,這個顯然是不合理的。下面我們學習一下,指定頭信息:url

// 經過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('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)
  })
相關文章
相關標籤/搜索