fetch 封装

import qs from "qs"

export default function ajax(url,params={},type='GET')
{
    // url='http://127.0.0.1:3000'+url;
    if(type=='GET')
    {
        let str='';
       Object.keys(params).forEach((item,index)=>{
            str+=item+'='+params[item]+'&';
       })
       if(str)
       {
           str=str.substring(0,str.length-1);
           str='?'+str;
       }
       return fetch(url+str).then(data=>data.json()) 
    }else{

        return fetch(url,{
            method:'POST',
            headers:{
                'Accept': 'application/json, text/plain, */*',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body:qs.stringify(params)
        }).then(data=>data.json())
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43294560/article/details/108407385