fetch的基本使用
一、使用fetch发送基本get请求
fetch('http://ajax-base-api-t.itheima.net/api/getbooks').then(res => {
//直接得到的res,是一个Response对象,需要通过特定的方法获取其中的内容
console.log(res) //Response{type:... ,url:...,status:200,... }
//res.json()是一个异步操作,表示取出所有的内容,将其转换成JSON对象
//console.log(res.json()); //结果:Promise{<pending>} 需要.then出来
return res.json()
}).then(json => {
//获得经过res.json()处理过之后的数据
console.log(json) // 结果 :{status:200,msg:...,data:Array(3)}
}).catch(err => {
console.log(err) //捕获错误信息
})
分析:
- fetch()只接受一个url,表示默认向该网址发送get请求,返回一个Promise对象
- 如果需要设置get参数,直接拼接到url地址上即可
- 语法:
fetch(url) .then(...) .catch(...)
改进:
- 把代码封装成async异步函数
- 如果需要通过get请求设置查询参数如何实现?
地址栏拼接查询参数 ---> url?name=value&name=value
async function getData() {
//通过try...catch处理async和await成功和失败的情况
try {
let res = await fetch("http://ajax-base-api-t.itheima.net/api/getbooks?id=2");
console.log(res);
let json = await res.json();
console.log(json);
} catch (err) {
console.log(err);
}
}
getData();
Response对象 (了解)
fench请求成功后,得到的是一个Response对象,它是服务器的HTTP响应
常用方法res.json()得到json对象
async function getData(){
let res = await fetch('http://ajax-base-api-t.itheima.net/api/getbooks')
console.log(res)
console.log(res.ok) //返回布尔类型,表示是否成功
console.log(res.status) //返回数字,表示请求是否成功
console.log(res.statusText) //返回状态文本信息(如:OK)
console.log(res.url) //返回url地址
}
二、使用fetch发送基本post请求
async function add(){
let obj = {
bookname:'魔法书之如何快速学好前端2',
author:'阿尼亚',
publisher: '格兰芬多'
}
try{
let res = await fetch('http://ajax-base-api-t.itheima.net/api/addbook',{
method:'post',
headers:{
'Content-Type': 'application/json'
},
body:JSON.stringify(obj)
})
let json = await res.json()
console.log(json)
} catch (err) {
console.log(err)
}
}
add()
分析:
fetch第一个参数是url,还可以接受第二个参数,作为配置对象,可以自定义发出的HTTP请求,如:
fetch(url,options)
其中:post、put、patch用法类似
配置参数介绍:
fetch(url,{
method:'请求方式,如post、delete、put',
headers:{
'Content-Type':'数据格式'
},
body:'post请求体数据'
})
三、fetch函数封装
http.js
async function http(obj) {
// 解构赋值
let { method, url, params , data } = obj
console.log(method, url, params , data);
// 处理params参数,如果有,转化为key=value&key=value,拼接到url上
if(params) {
let str = new URLSearchParams(params).toString()
url += "?" + str;
}
// 处理data,如果有需写完整的代码headers...
let res
if(data) {
res = await fetch(url,{
method:method,
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify(data)
})
} else {
res = await fetch(url)
}
return res.json();
}
分析:
- get delete 的请求参数,要在地址栏拼接
- put patch post 的请求参数,要转json设置请求头
//发送get、delete请求
http({
method:'xxx',
url:'xxx',
params:{......}
})
//发送post、put、patch请求
http({
method:'xxx',
url:'xxx',
data:{......}
})
调用封装后的fetch函数
async function fn1(){
let result = await http({
method:'get',
url:'http://ajax-base-api-t.itheima.net/api/getbooks',
params:{
id:2
}
})
console.log(result)
}
fn1()
async function fn2(){
let result = await http({
method:'post',
url:'http://ajax-base-api-t.itheima.net/api/addbook',
data:{
bookname:'魔法书之如何快速学好前端2',
author:'阿尼亚',
publisher: '格兰芬多'
}
})
console.log(result)
}
fn2()