JavaScript fetch接口


JavaScript fetch接口

fetch,說白了,就是XMLHttpRequest的一種替代方案。如果有人問你,除了Ajax獲取后台數據之外,還有沒有其他的替代方案?

這是你就可以回答,除了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還可以提供第二個參數,就是用來傳遞一些初始化的信息。

這里如果要特別指明是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請求

與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) })

設置請求的頭信息

在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('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) })


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM