97

前端技术整理之fetch

 6 years ago
source link: https://juejin.im/post/5a60031f6fb9a01cb0495d1d
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.



161070c309b8961c~tplv-t2oaga2asx-zoom-in-crop-mark:4536:0:0:0.awebp


vbnet

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提供了更强大和灵活的功能集。

这是官方API中的第一句话,可以看出fetch是Web API中新增的,用于取代XMLHttpRequest的网络请求框架,它比之更强大。下面我们来下它的使用。

Fetch

fetch返回的其实是一个Promise函数。我们先来看一个完整的请求代码:



javascript

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对象,包括一下几种:

  • 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 对象。

Response对象:

    • 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)的差异


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK