fetch 踩过许多坑后 才 得到 的 正确格式

fetch

不跨域,api  , 替代ajax   单纯  的写法   

第一种写法:

function aaa(obj,src)
        {       
            let postData = {a:'b'};
            let ret = fetch(url, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': "token",
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(postData)
            })//必须两个then 才能得到正常的json
            .then(response=>response.json())
            .then(data=>{
                //这里才得到json
            })
        }

第二种写法:

/**
  *    使用async  await
  */
async function delImg(obj,src)
        {        
            let postData = {a:'b'};            
            let ret = await fetch(url, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': "token",
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(postData)
            })
                //格式化返回的数据
                let response =await ret.json();
               if (response.status === )
               {
                //在这里处理业务逻辑   
               }
        }

猜你喜欢

转载自www.cnblogs.com/zqblog1314/p/12740296.html