美文网首页
Fetch 函数的封装

Fetch 函数的封装

作者: 热心程序猿黄帅哥 | 来源:发表于2018-09-03 16:27 被阅读0次

/**

* Fetch封装函数:进行前后台接口数据交互

*/

/**

* 将对象转成 a=1&b=2的形式

* @param obj 对象

*/

function obj2String(obj, arr = [], idx = 0) {

    for (let item in obj) {

        arr[idx++] = [item, obj[item]]

    }

    return new URLSearchParams(arr).toString()

}

/**

* 真正的请求

* @param url 请求地址

* @param options 请求参数

* @param method 请求方式

*/

function commonFetcdh(url, options, callBackfn, method = 'GET') {

    const searchStr = obj2String(options);

    let initObj = {}

    if (method === 'GET') { // 如果是GET请求,拼接url

        url += '?' + searchStr

        initObj = {

            method: method,

            credentials: 'include'

        }

    } else {

        initObj = {

            method: method,

            credentials: 'include',

            headers: new Headers({

                'Accept': 'application/json',

                'Content-Type': 'application/x-www-form-urlencoded'

            }),

            body: searchStr,

            mode:"cors"

        }

    }

    fetch(url, initObj).then((res) => {

        // console.log(res, 1212)

        return res.json()  // 返回一个Promise,可以解析成JSON

    }).then((data) => {

        // console.log(data, "回馈信息")

        callBackfn(data)

    })

}

/**

* GET请求

* @param url 请求地址

* @param options 请求参数

* @param callBackfn 回调函数

*/

export function GET(url, options, callBackfn) {

    return commonFetcdh(url, options, callBackfn, 'GET')

}

/**

* POST请求

* @param url 请求地址

* @param options 请求参数

* @param callBackfn 回调函数

*/

export function POST(url, options, callBackfn) {

    return commonFetcdh(url, options, callBackfn, 'POST')

}

相关文章

网友评论

      本文标题:Fetch 函数的封装

      本文链接:https://www.haomeiwen.com/subject/sehiwftx.html