The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set.
複製代碼
Fetch API 提供了一個獲取資源的接口(包括跨域)。任何使用過 XMLHttpRequest
的人都能輕鬆上手,但新的API提供了更強大和靈活的功能集。html
這是官方API中的第一句話,能夠看出fetch
是Web API中新增的,用於取代XMLHttpRequest
的網絡請求框架,它比之更強大。下面咱們來下它的使用。json
fetch返回的實際上是一個Promise
函數。咱們先來看一個完整的請求代碼:跨域
const url = '192.168.32.45:8081/login.shtml'
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: 'fll',
password: '123'
})
})
.then((response) => {
if(response.status == 200) {
return response
}
})
.then((data) => {
return data.text()
}).then((text) => {
console.log('請求成功', text)
}).catch((err) => {
console.log('請求錯誤', err)
})
複製代碼
fetch的參數有兩個參數,第一個是url,就是請求的路徑;緩存
另外一個是Request
對象,包括一下幾種:bash
method
: 請求方法:GET
、POST
。headers
:請求頭信息,形式爲Headers
對象或者ByteString
。上述例子就是一個json請求的請求頭。body
: 請求參數:多是一個 Blob
、BufferSource
、FormData
、URLSearchParams
或者 USVString
對象。注意 GET
或 HEAD
方法的請求不能包含 body
信息。mode
:請求的模式。如 cors
, no-cors
, same-origin
, navigate
cache
: 緩存模式,如default
, reload
, no-cache
更多的信息請看Reques服務器
若是你對請求頭不太熟悉的,能夠看這裏Headers網絡
上面咱們說了fetch的返回的是一個Promise
對象。而後會攜帶Response
對象。app
Response
對象:cors
屬性:框架
status (number)
- HTTP請求結果參數,在100–599 範圍, 200 爲成功statusText (String)
- 服務器返回的狀態報告ok (boolean)
- 若是返回200表示請求成功則爲trueheaders (Headers)
- 返回頭部信息,下面詳細介紹url(String)
請求的地址方法:
text()
以string
的形式生成請求textjson
生成JSON.parse(responseText)的結果blob
生成一個Blob
arrayBuffer()
生成一個ArrayBuffer
formData
生成格式化的數據,用於其餘請求其餘方法:
clone()
Response.error()
Response.redirect()
response.headers
has(name) (boolean)
判斷是否存在該信息頭get(name) (String)
獲取信息頭的數據getAll(name) (Array)
獲取全部頭部數據set(name, value)
添加headers的內容delete(name)
刪除header的信息forEach
循環讀取header的信息