前端技术整理之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)的差别

相关文章
相关标签/搜索