基本用法
GET
axios.get("http://localhost:8000/api/...").then((res) => {
console.log(res.data);
});
const res = await axios.get("http://localhost:8000/api/...");
console.log(res.data)
fetch("http://localhost:8000/api/...")
.then((res)=>res.text())
.then(console.log)
const res = await fetch("http://localhost:8000/api/...");
const data = await res.text();
console.log(data)
POST(json+header)
const params = {
name:"zhangsan"
};
const headers = {
"token":"..."
};
axios.post(url,params,{headers})
const params = {
name:"zhangsan"
};
const headers = {
"token":"...",
"Content-Type":"application/json"
};
fetch(url,{
method:"POST",
body:JSON.stringify(params),
headers
})
POST(formdata)
const form = new FormData();
form.append("name","zhangsan");
form.append("file",file);
axios.post(url,form)
axios.postForm(url,{
name:"zhangsan",
_file:file
})
const form = new FormData();
form.append("name","zhangsan");
form.append("file",file);
fetch(url,{
method:"POST",
body:form
})
数据流
axios.get(url,{
responseType:"arraybuffer"
})
.then((res)=>{
// 传输完成后处理res.data
})
fetch(url).then((res)=>{
const reader = res.body.getReader();
})
中止请求
const controller = new AbortController();
axios.get(url,{
signal:controllerq.signal
})
controller.abort();
fetch(url,{
signal:controller.signal
})
controller.abort();
请求超时
axios.get(url,{
timeout:5000
})
.catch((err)=>{
if(err.code === "ECONNABORTED"){
// 超时处理
}
})
fetch(url,{
signal: AbortSignal.timeout(5000)
})
.catch((err)=>{
if(err.name === "TimeoutError"){
// 超时处理
}
})
进度监控
axios.post(url,formData,{
onUploadProgress:(e)=>{
const percent = Math.round((e.loaded * 100) / e.total);
console.log(`上传进度:${percent}%`)
}
})
axios.get(url,{
responseType:"arraybuffer",
onDownloadProgress:(e)=>{
const percent = Math.round((e.loaded * 100) / e.total);
console.log(`下载进度:${percent}%`)
}
})
const response = await fetch(url);
const reader = response.body.getReader();
const total = +response.headers.get("Content-Length");
let received = 0;
while(true){
const {done,value} = await reader.read();
if(done){
break;
}
received += value.length;
console.log(`下载进度:${Math.round((received * 100) / total)}%`)
}
兼容性
总结