fetch 处理网络请求
(1)基本使用
get请求
fetch('路径')
//返回响应对象,并要求为json格式
.then(data=>{return data.json()}) data.ok返回是否成功,可改写成if(data.ok){return data.json()}
//返回真实数据
.then(res=>{xxx})
使用async、await语法糖
fetch('路径').then(async (res)=>{
if(res.ok){
let data=await res.json()
}
})
post请求
fetch('路径',{
method:'POST',
//设置请求头
headers:{
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/x-www-form-urlencoded'
},
body:"传入的键值对参数,以&分割" 或使用qs.stringify(对象),import qs from "qs"
}).then(data=>{return data.json()})
.then(res=>{xxx})
(2)中断请求
const controller = new AbortController()
const signal = controller.signal
fetch('/todos', {
method: 'get',
signal,
})
中断:controller.abort()
(3)将对象的内容,转成url参数形式
function fun(obj)
{
var res='';
for(var key in obj)
{
res+='&'+key+'='+encodeURIComponent(obj[key]);
}
if(result)
{
//去掉开头的'&'
res=res.slice(1);
}
return res;
}
代码示例:
import qs from "qs"
var flag=false;
if(flag)
{
//get请求
fetch('http://localhost:3000/news')
.then(data=>{ return data.json()})
.then(res=>{ console.log(res)})
}else{
//post请求
fetch('http://localhost:3000/news',{
method:'POST',
headers:{
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/x-www-form-urlencoded'
},
body:"id=jeff"
}).then(data=>{ return data.json()})
.then(res=>{ console.log(res)})
}
export function getData(url) {
const result = fetch(url);
return result;
}
export function postData(url,data) {
const result = fetch(url, {
method: "post",
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/x-www-form-urlencoded'
},
body:qs.stringify(data)
})
console.log(qs.stringify(data));
return result;
}
还没有评论,来说两句吧...