fetch小结
fetch小结
get请求
默认是get请求
fetch("url")
get请求携带参数
const listQuery = {
name:"杨瑞堂",
age:12,
address:"浙江省舟山市普陀区东极镇"
}
const params = new URLSearchParams()
Object.entries(listQuery).forEach(item=>{
params.append(item[0],item[1])
})
fetch("url?"+params.toString())
post请求
fetch通过第二个参数进行请求配置
fetch("url",{
method:"POST"
})
post携带不同格式参数
json
const listQuery = {
name:"杨瑞堂",
age:12,
address:"浙江省舟山市普陀区东极镇"
}
fetch("url",{
method:"POST",
headers:{//设置请求头为 json
"content-type":"application/json"
},
body:JSON.stringify(listQuery)//同时将对象序列化
})
application/x-www-form-urlencoded
fetch("url",{
method:"POST",
headers:{
"content-type":"application/x-www-form-urlencoded"
},
body:"name=张三&age=24"
})
multipart/form-data
const formData = new FormData();
formData.append('username', 'abc123');
fetch('https://example.com/profile/avatar', {
method: 'PUT',
body: formData
})
检查请求是否成功
fetch('url')
.then(response => {
if (!response.ok) {//当请求 code 为 200-299 时,返回true
throw new Error('Network response was not OK');
}
return response.blob();
})
.then(myBlob => {
myImage.src = URL.createObjectURL(myBlob);
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});

浙公网安备 33010602011771号