前端技术整理之fetch
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.
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
函数。我们先来看一个完整的请求代码:
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
: 请求方法: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
Response
上面我们说了fetch的返回的是一个Promise
对象。然后会携带Response
对象。
Response
对象:
-
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的信息
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK