# 40.fetch概述
# 1.基本特性
- 更加简单的数据获取方式, 功能更强大, 更灵活, 可以看做是xhr的升级版
- 基于Promise实现
# 2.语法结构
fetch(url).then(fn2)
.then(fn3)
...
.catch(fn)
1
2
3
4
2
3
4
官方: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
# 3.fetch的基本用法
- fetch不是ajax的进一步封装,而是原生js,没有使用XMLHttpRequest对象。
fetch('/abc').then(data=>{
// text()方法属于fetchAPI的一部分,它返回一个Promise实例对象,用于获取后台返回的数据
return data.text()
}).then(ret => {
// 注意这里得到的才是最终的数据
console.log(ret);
})
1
2
3
4
5
6
7
2
3
4
5
6
7
# 4.fetch请求参数
# 1).常用配置选项
- method(String):HTTP请求方法, 默认为GET(GET, POST, PUT, DELETE)
- body(String):HTTP的请求参数
- headers(Object):HTTP的请求头, 默认为{}
fetch('/abc', {
method: 'get'
}).then(data => {
return data.text()
}).then(ret => {
// 注意这里得到的才是最终的数据
console.log(ret)
})
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 2).GET请求方式的参数传递
fetch('/abc?id=123',{
method: 'get'
}).then(data => {
return data.text();
}).then(ret => {
// 注意这里得到的才是最终的数据
console.log(ret)
})
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
Restful风格:
fetch('/abc/123', {
method: 'get'
}).then(data => {
return data.text();
}).then(ret => {
// 注意这里得到的才是最终的数据
console.log(ret)
})
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 3).DELETE请求方式的参数传递
fetch('/abc/123', {
method: 'delete'
}).then(data => {
return data.text();
}).then(ret => {
// 注意这里得到的才是最终的数据
console.log(ret)
})
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 4).POST请求方式的参数传递
fetch('http://localhost:3000/books', {
method: 'post',
body: 'uname=lisi&pwd=123',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}).then(data => {
return data.text()
}).then(ret => {
console.log(ret)
})
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
json格式:
fetch('http://localhost:3000/books', {
method: 'post',
body: JSON.stringify({
uname: 'lisi',
age: 12
}),
headers: {
'Content-Type': 'application/json',
}
}).then(data => {
return data.text()
}).then(ret => {
console.log(ret)
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 5).PUT请求方式的参数传递
fetch('http://localhost:3000/books/123', {
method: 'put',
body: JSON.stringify({
uname: 'lisi',
age: 12
}),
headers: {
'Content-Type': 'application/json',
}
}).then(data => {
return data.text()
}).then(ret => {
console.log(ret)
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 5.fetch响应结果
响应数据格式
- text(): 将返回体处理成字符串类型
- json(): 返回结果和JSON.parse(responseText)一样
fetch('http://localhost:3000/json').then(function(data){
// return data.json(); // 将获取到的数据使用 json 转换对象
return data.text(); // // 将获取到的数据 转换成字符串
}).then(function(data){
// console.log(data.uname)
// console.log(typeof data)
var obj = JSON.parse(data);
console.log(obj.uname,obj.age,obj.gender)
})
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
← 39.promise 41.axios →