fetch发送get请求
<script>
fetch('http://ajax-base-api-t.itheima.net/api/getbooks').then(res=>{
// 直接得到的res是一个Response对象,需要通过特定的方法获取其中的内容
console.log("res",res)
// res.json()是一个异步操作,表示取出所有的内容,将其换成JSON对象
// console.log(res.json())
return res.json() // 返回的是一个promise对象
}).then(json=>{
// 这个json是经过res.json()处理过之后的数据
console.log("json",json) // 返回一个JavaScript对象
}).catch(err=>{
console.log(err)
})
</script>
类比理解
可以把 res.json() 想象成一个 快递包裹:
- 第一个
.then():你收到一个包裹(Response),但需要拆开(res.json())res.json()是“拆包裹的动作”,返回的是“拆箱承诺”(Promise)
- 第二个
.then():拆箱完成后,你才能拿到里面的物品(实际数据)
使用async-await改写
<script>
// 声明函数 使用async await
async function getData(){
let res = await fetch('http://ajax-base-api-t.itheima.net/api/getbooks')
console.log(res)
// res.json()是一个异步操作,可以使用await 取出response对象中的结果
let json = await res.json()
console.log(json)
}
// 调用函数
getData()
</script>
如果需要提供get请求设置查询参数该如何实现
可以通过地址栏拼接查询参数====》url?name=value&name=value
如fetch('http://ajax-base-api-t.itheima.net/api/getbooks?id=2')
Response对象的基本了解
<script>
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) //返回状态的文本信息(例如:请求成功之后,服务器会返回OK)
console.log(res.url) //返回请求的URL
let json = await res.json()
console.log(json)
}
getData()
</script>
fetch配置参数
fetch的第一个参数是url,此外还可以接收第二个参数,作为配置对象,可以自定义发出的http请求,比如fetch(url,options)
其中post、put、patch用法类似,此处一post为例
fetch配置参数介绍
fetch(url, {
method:'请求方式,比如:post、delete、put',
headers:{
'Content-Type':'数据格式'
},
body:'post请求体数据'
}
fetch发送post请求
<script>
async function add() {
let obj = {
bookname:'魔法书之快速学好前端trwg',
author:'afa',
publisher:'fdsag'
}
let res = await fetch('http://ajax-base-api-t.itheima.net/api/addbook',{
method:'post',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify(obj) // 将对象转换为JSON字符串
})
let json = await res.json()
console.log(json)
}
add()
</script>
fetch函数封装
原生的fetch虽然已经支持promise了,相比较XMLHttpResquest已经好用很多了,但是参数还是需要自己处理,比较麻烦,可以对fetch函数进行二次封装。
<script>
// 封装http函数(fetch请求)
async function http(obj) {
// console.log("get和post请求传过来的数据:",obj)
// 解构赋值
let {method,url,params,data} = obj
console.log("===",method,url,params,data)
// params需要处理===》转换成key=value&key=value
// 1、如果有params参数,则把params对象转换成key=value&key=value的形式,并且需要拼接到url之后
// 2、如果没有params参数,则不管
if (params) {
// 有params
// 使用了 URLSearchParams 来处理查询参数
// 固定写法:new URLSearchParams(obj).toString()
let str = new URLSearchParams(params).toString()
console.log(str)
// url += str
// console.log("拼接了参数的URL",url) // 发现少了问号
url += '?' + str
console.log(url)
}
// data需要处理
// 1、如果有data,此时需要写完整的代码hesaders
// 2、如果没有data,则不需要设置headers,直接发送即可
let res
if(data){
// 设置了data
res = await fetch(url,{
method:method,
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify(data)
})
} else {
// 没有data
res = await fetch(url)
}
// 把获取的结果经过处理之后返回出去
return res.json()
}
// get请求示例
async function fn1() {
let result = await http({
method:'get',
url:'http://ajax-base-api-t.itheima.net/api/getbooks',
params:{
id:2
}
})
console.log("get请求:",result)
}
fn1()
// post请求示例
async function fn2() {
let result = await http({
method:'post',
url:'http://ajax-base-api-t.itheima.net/api/addbook',
data:{
bookname:'前端高薪就业',
author:'fsdjfji',
publisher:'fsger'
}
})
console.log("post请求:",result)
}
fn2()
</script>
控制台输出