Fetch是Es6提出的用于替代XMLHttpRequest,用于访问和操纵HTTP,由于Fetch使用了ES6的promise对象,所以解决了令人诟病的回调地域问题,是一种更加优雅的请求方式。
小例子
<script>
fetch('https://smallpig.site/api/category/getCategory').then(res => res.json()).then(data => {
console.log(data)
})
</script>
输出结果:
参数
<script>
const url = 'http://192.168.32.45:8081/login.shtml'
const params = {
name: '张三',
age: 18
}
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
})
.then(response => {
if (response.status === 200) return response
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err))
</script>
fetch有两个参数,第一个url,,第二个request对象
Request对象
- method: 请求方法,如GET、POST
- headers: 请求头信息
- body: 请求参数,可以是Blob、BufferSource、FormData、URLSearchParams或者USVString对象,注意GET或HEAD方法不能包含body
- mode: 请求模式。如cors no-cors same-origin navigate
- cache: 缓存模式。如default,reload,no-cache
Response对象
- status: 请求结果状态,如200
- statusText: 服务器返回的状态报告
- ok: 请求成功状态,布尔值
- headers: 返回的头部信息
- url: 请求的地址
方法
- text()
- json()
- blob()
- arrayBuffer()
- formData()
- clone()
- Response.error()
- Response.redirect()
文章仅作为个人学习和整理!