前端技術整理之fetch

前言

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

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

另外一個是Request對象,包括一下幾種:bash

  • method: 請求方法:GETPOST
  • headers:請求頭信息,形式爲Headers對象或者ByteString。上述例子就是一個json請求的請求頭。
  • body: 請求參數:多是一個 BlobBufferSourceFormDataURLSearchParams 或者 USVString 對象。注意 GETHEAD 方法的請求不能包含 body 信息。
  • mode:請求的模式。如 cors, no-cors, same-origin, navigate
  • cache: 緩存模式,如default, reload, no-cache

更多的信息請看Reques服務器

若是你對請求頭不太熟悉的,能夠看這裏Headers網絡

Response

上面咱們說了fetch的返回的是一個Promise對象。而後會攜帶Response 對象。app

Response對象:cors

  • 屬性:框架

    • status (number) - HTTP請求結果參數,在100–599 範圍, 200 爲成功
    • statusText (String) - 服務器返回的狀態報告
    • ok (boolean) - 若是返回200表示請求成功則爲true
    • headers (Headers) - 返回頭部信息,下面詳細介紹
    • url(String) 請求的地址
  • 方法:

    • text()string的形式生成請求text
    • json 生成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的信息

參考資料

ES6的Fetch異步請求

Fetch官方API

fetch API 和 Ajax(XMLHttpRequest)的差別

相關文章
相關標籤/搜索