前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >react-开发经验分享-自定义封装请求方法(一)

react-开发经验分享-自定义封装请求方法(一)

作者头像
Mr. 柳上原
发布2018-12-25 14:41:09
1.2K0
发布2018-12-25 14:41:09
举报
文章被收录于专栏:菜鸟前端工程师

Author:Mr.柳上原

  • 付出不亚于任何的努力
  • 愿我们所有的努力,都不会被生活辜负
  • 不忘初心,方得始终

react里,请务必自己封装请求方法 好处:1.自定义封装请求方法,能够更好的处理请求结构,做好请求体body的处理等 2.可以使用多种异步数据请求方法,如Promise.then().catch(),async 》 await,try,catch等 3.请求方法的复用性(这才是react的精髓) 4.颗粒化思想, 5.可以简化具体页面的后端请求结构,细致拆分组件,精准定位bug

代码语言:javascript
复制
// 接口封装方法

// 接口验证的公用判断方法
export async function callApi(call) {
    try {
        let response = await call();
        response = (response || {}).data || {};
        return response;
    } catch (e) {
        return { code: "500", message: e.message }
    }
}

// 接口封装
const ApiClient = {
    get(url, useToken = true, qs) {

        const headers = new Headers();
        headers.append('Accept', 'application/json');
        if (useToken) {
            const token = store.getState().oidc.user.access_token;
            headers.append('Authorization', `Bearer ${token}`);
        }
        const options = {
            method: 'GET',
            headers,
            mode: 'cors'
        };
        const params = new URLSearchParams();
        if (qs) {
            Object.keys(qs).forEach(key => params.append(key, qs[key]));
            url = url + "?" + params.toString();
        }


        return fetch(url, options)
            .then((res) => res.json())
            .then((data) => ({ data }))
            .catch((error) => ({ error }));
    },
    getWithnoToken(url, header, qs) {

        const headers = new Headers();
        headers.append('Accept', 'application/json');
        if (header) {
            // headers.append('Authorization', `Bearer ${token}`);
            // console.log("userToken:", `Bearer ${token}`);
            Object.keys(header).forEach(key => headers.append(key, header[key]))
        }
        const options = {
            method: 'GET',
            headers,
            mode: 'cors'
        };
        const params = new URLSearchParams();
        if (qs) {
            Object.keys(qs).forEach(key => params.append(key, qs[key]));
            url = url + "?" + params.toString();
        }
        return fetch(url, options)
            .then((res) => res.json())
            .then((data) => ({ data }))
            .catch((error) => ({ error }));
    },
    post(url, body, qs, method = 'POST') {
        const token = store.getState().oidc.user.access_token;
        const headers = new Headers();
        headers.append('Content-Type', 'application/json');
        headers.append('Accept', 'application/json');
        headers.append('Authorization', `Bearer ${token}`);

        var postData = undefined;
        if (body) {
            postData = JSON.stringify(body);
        }

        const options = {
            method: method,
            headers,
            mode: 'cors',
            body: postData
        };

        const params = new URLSearchParams();
        if (qs) {
            Object.keys(qs).forEach(key => params.append(key, qs[key]));
            url = url + "?" + params.toString();
        }

        return fetch(url, options)
            .then((res) => res.json())
            .then((data) => ({ data }))
            .catch((error) => ({ error }));
    },
    postForm(url, body, qs, method = 'POST', headerSetter) {
        const headers = new Headers();
        headers.append('Accept', 'application/json');
        if (headerSetter) {
            headerSetter(headers);
        }
        const params = new URLSearchParams();
        if (qs) {
            Object.keys(qs).forEach(key => params.append(key, qs[key]));
            url = url + "?" + params.toString();
        }
        //   headers.append('Authorization', `Bearer ${token}`);


        const options = {
            method: method,
            headers,
            mode: 'cors'
        };
        var fd = new FormData();
        if (body) {
            for (var k in body) {
                if (body.hasOwnProperty(k)) {
                    fd.append(k, body[k]);
                }
            }
            options.body = fd;
        }


        return fetch(url, options)
            .then((res) => res.json())
            .then((data) => ({ data }));
    },
    postFormUrlEncode(url, body, qs, method = 'POST', headerSetter) {
        const headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        headers.append('Accept', 'application/json');
        if (headerSetter) {
            headerSetter(headers);
        }
        const params = new URLSearchParams();
        if (qs) {
            Object.keys(qs).forEach(key => params.append(key, qs[key]));
            url = url + "?" + params.toString();
        }

        const options = {
            method: method,
            headers,
            mode: 'cors'
        };
        if (body) {
            const bodyParams = new URLSearchParams();

            Object.keys(body).forEach(key => bodyParams.append(key, body[key]));
            options.body = bodyParams.toString();

        }

        return fetch(url, options)
            .then((res) => res.json())
            .then((data) => ({ data }));
    },
    put(url, body, qs, method = 'PUT') {
        const token = store.getState().oidc.user.access_token;
        const headers = new Headers();
        headers.append('Content-Type', 'application/json');
        headers.append('Accept', 'application/json');
        headers.append('Authorization', `Bearer ${token}`);

        var postData = undefined;
        if (body) {
            postData = JSON.stringify(body);
        }

        const options = {
            method: method,
            headers,
            mode: 'cors',
            body: postData
        };

        const params = new URLSearchParams();
        if (qs) {
            Object.keys(qs).forEach(key => params.append(key, qs[key]));
            url = url + "?" + params.toString();
        }
        return fetch(url, options)
            .then((res) => res.json())
            .then((data) => ({ data }))
            .catch((error) => ({ error }));
    },
    del(url, body, qs, method = 'DELETE') {
        const token = store.getState().oidc.user.access_token;
        const headers = new Headers();
        headers.append('Content-Type', 'application/json');
        headers.append('Accept', 'application/json');
        headers.append('Authorization', `Bearer ${token}`);

        var postData = undefined;
        if (body) {
            postData = JSON.stringify(body);
        }

        const options = {
            method: method,
            headers,
            mode: 'cors',
            body: postData
        };

        const params = new URLSearchParams();
        if (qs) {
            Object.keys(qs).forEach(key => params.append(key, qs[key]));
            url = url + "?" + params.toString();
        }
        return fetch(url, options)
            .then((res) => res.json())
            .then((data) => ({ data }))
            .catch((error) => ({ error }));
    }
}


export default ApiClient;
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.12.10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档