fetch小结
get请求
默认是get请求
fetch("url")
post请求
fetch通过第二个参数进行请求配置
fetch("url",{
method:"POST"
})
post携带不同格式参数
json
fetch("url",{
method:"POST",
headers:{
"content-type":"application/json"
},
body:JSON.stringify(data)
})
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) {
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);
});
标签:application,url,fetch,method,error,小结,response
From: https://www.cnblogs.com/letgofishing/p/17019709.html