美文网首页
ReactNative HttpUtils 工具类

ReactNative HttpUtils 工具类

作者: 月落吖 | 来源:发表于2019-04-23 19:35 被阅读0次

HttpUtils 工具类


const formData = Symbol();

export default class IHttpUtils {

    /**
     * GET 请求
     *
     * @static
     * @param {*} { url }
     * @returns
     * @memberof IHttpUtils
     */
    static get({ url }){
        return new Promise((resolve, reject)=> {
            fetch(url)
                .then(response => response.json())
                .then(responseJson => {
                    resolve(responseJson);
                })
                .catch(error => {
                    reject(error);
                })
        })
    }

    /**
     * POST 请求
     *
     * @static
     * @param {*} { url, data }
     * @returns
     * @memberof IHttpUtils
     */
    static post({ url, data }){
        return new Promise((resolve,reject)=> {
            fetch(url, {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type':'application/x-www-form-urlencoded'
                },
                body: this[formData](data)
            })
                .then(response=>response.json())
                .then(result=> {
                    resolve(result);
                })
                .catch(error=>{
                    reject(error);
                })
        })
    }

    /**
     * 对象转表单数据
     *
     * @static
     * @param {*} data
     * @returns
     * @memberof IHttpUtils
     */
    static [formData] (data) {
        let str = '';
        for (const key in data) {
            str += `${key}=${data[key]}&`;
        }
        return str.replace(/&$/, '');
    }

}

使用说明

import IHttpUtils from '../../utils/IHttpUtils'
IHttpUtils.get({
                  url: 'https://www.apiopen.top/weatherApi?city=北京'
              })
              .then(res => console.log(res))
              .catch(err => console.log(err);
 IHttpUtils.post({
                        url: 'https://www.apiopen.top/satinApi',
                        data: {
                          type: 1,
                          page: 1
                        }
                 })
                 .then(res => {console.log(res))
                 .catch(err => console.log(err);

相关文章

网友评论

      本文标题:ReactNative HttpUtils 工具类

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