- 更加简单的数据获取方式,功能更强大,灵活,xhr的升级版
- 基于Promise实现
- 文档
请求参数
常用配置选项
- method(string) HTTP请求方法,默认GET(GET,POST,PTU,DELETE)
- body(string) HTTP请求参数
- headers(obj) HTTP请求头,默认{}
响应数据格式
- text() : 将返回体处理成字符串类型
- json() :将返回结果和JSON.parse(reponesText)一样
fetch(url,{
method: 'post',
body:JSON.stringify({
uname : 'yomuki',
age : 12
}),
headers: {
'Contnet-Type' : 'application/json',
}
}).then(
data => {
//返回字符串形式
// return data.text();
return data.json();
}
).then(
ret => {
console.log(ret)
//text : [{"id":1,"name":"张三"},{"id":2,"name":"木木"},{"id":3,"name":"小酒"},{"id":4,"name":"萝卜"}]
//json : Array(4) [ {…}, {…}, {…}, {…} ]
}
).catch(error => console.log(error))