当前位置: 首页 > Web前端 > HTML

fetch简单的封装了request.js

时间:2023-03-28 19:26:04 HTML

constprefixUrl='http://test-api.xxx.com'//测试//constprefixUrl='https://api.xxx.com'//生产//get请求封装constfetchGet=function({url,参数}){让列表=[];for(letkeyinparams){letstr=`${key}=${params[key]}`list.push(str);}constdata=list.join('&');让allUrl=`${prefixUrl+url}?${data}`;constoptions={method:'GET',headers:{Accept:'application/json','Content-Type':'application/json;charset=UTF-8',},}returnfetch(allUrl,选项).then(res=>{returnres.json();}).catch(err=>{console.log(err);});};//post请求封装constfetchPost=function({url,params}){constoptions={method:'POST',headers:{Accept:'application/json','Content-Type':'application/json;charset=UTF-8',},body:JSON.stringify(params),}returnfetch(prefixUrl+url,options).then(res=>{returnres.json();}).catch(err=>{console.log(err);})};export{fetchGet,fetchPost,}api.js使用import{fetchGet}from'./request'exportfunctiongetXXX(params){returnfetchGet({url:'/xxxxx',params:params})}