美文网首页
reactnative 使用axios封装网络请求

reactnative 使用axios封装网络请求

作者: 米开朗骑騾 | 来源:发表于2019-02-22 16:05 被阅读0次

参考

import axios from 'axios';
import qs from 'querystring';
import DeviceInfo from 'react-native-device-info';
import LoadingUtil from "./LoadingUtil";
import {env, apiUrls} from '../../app.json';
let defaultConfig = {
    // baseUrl: 'http://10.0.0.90:8200',//测试
    baseUrl: apiUrls[env],
    timeout: 60000,
    headers: {
        'deviceId': DeviceInfo.getUniqueID(),
        'version': DeviceInfo.getVersion(),
    }
};

let instance = axios;
let baseUrl = defaultConfig.baseUrl + "/";

class Axios {
    constructor(props) {
        if (props && typeof props === 'object') {
            instance = axios.create(props);
        } else {
            instance = axios.create(defaultConfig);
        }

        //拦截
        instance.interceptors.request.use((config) => {
            return config
        }, (error) => {
            console.log(error);
            return Promise.reject(error)
        });

        //日志 响应结果
        instance.interceptors.response.use((response) => {
            return response.data
        }, (error) => {
            console.log(error);
            return Promise.reject(error)
        })
    }

    getUrl() {
        return defaultConfig.baseUrl;
    }

    async get(url) {
        return this.get(url, null)
    }

    async get(url, params) {
        try {
            LoadingUtil.showLoadingDelay(500);
            let query = await qs.stringify(params);
            let response = null;
            // console.log(baseUrl + url, params)
            if (!params) {
                response = await instance.get(baseUrl + url);
            } else {
                response = await instance.get(baseUrl + url + '?' + query);
            }
            LoadingUtil.dismissLoading();
            return response
        } catch (e) {
            LoadingUtil.dismissLoading();
            console.log(e);
            return null
        }
    }

    async post(url) {
        return this.post(url, null, true, true)
    }

    async post(url, params, showLoading = true, showError = true) {
        try {
            if (showLoading) {
                LoadingUtil.showLoadingDelay(500);
            }
            let response = await instance.post(baseUrl + url, params);
            // if (showLoading) {
                LoadingUtil.dismissLoading();
            // }
            // console.log(baseUrl + url, params)
            if (response) {
                if (response.code !== 0){
                    if (showError) {
                        global.toast.alertWithType('warn', '温馨提示',response.message);
                    }
                }
                if (response.code === 10011) {
                    // console.log("response.code error : " + response.code + " " + response.message);
                    
                } else if (response.code === 10012 || response.code === 10013 || response.code === 10014 || response.code === 20004) {
                    // console.log("response.code error2 : " + response.code + " " + response.message);
                    
                }
            }
            return response;
        } catch (e) {
            if (showLoading) {
                LoadingUtil.dismissLoading();
            }
            console.log(e);
            return null
        }
    }

    setPostHeader(key, value) {
        instance.defaults.headers.post[key] = value;
    }
}

export default http = new Axios();

api调用

import http from '../utils/Axios'


export async function createClub(params) {
    let ret = {};
    let response = await http.post('xxx/xxxx/xxx',params);
    if (response !== undefined) {
        ret = response;
        console.log("%s %O", "结果", response);
    }
    return ret;
}

saga处使用

import *as types from '../../constants/ClubTypes';
import {put, take, fork, cancel, call} from 'redux-saga/effects';
import {
    createClub,
} from '../../apis/ClubApi';
const createRequest = function* createRequest(action) {

    let data = yield call(createClub, action.params);

    if (data.code === 0) {
        yield put({
            type: types.CLUB_CREATE_SUCCESS,
            result: data.result,
        })
    } else {
        yield put({
            type: types.CLUB_CREATE_ERROR,
            message: data.message,
        });
    }
};

const watchRequestClub = function* watchRequestClub() {
    let lastTask;
    while (true) {
        const action = yield take([
        types.CLUB_CREATE_REQUEST,
        ]);
        if (lastTask) {
            yield cancel(lastTask)
        }
        yield put({type: types.CLUB_DOING});
        switch (action.type) {
            case types.CLUB_CREATE_REQUEST:
                lastTask = yield fork(createRequest, action);
                break;
 }
    }
};

export {watchRequestClub}

app.json用来切换服务即各种配置(地图、支付、推送、微信等)

{
    "name": "XXX",
    "displayName": "XXX",
    "env": "dev",
    "apiUrls": {
        "dev": "http:\/\/10.0.0.90:8200",
        "inner": "http:\/\/10.0.0.90:8200",
        "staging": "https:\/\/api.xxx.com",
        "prod": "https:\/\/api.xxx.com"
    },
    "amapKeyIos": {
        "dev": "*********************",
        "inner": "*********************",
        "staging": "*********************",
        "prod": "*********************"
    },
    "amapKeyAndroid": {
        "dev": "*********************",
        "inner": "*********************",
        "staging": "*********************",
        "prod": "*********************"
    },
    "iosPushName": {
        "dev": "iospushdev",
        "inner": "iospushdev",
        "staging": "iospush",
        "prod": "iospush"
    },
    "wxid": "*********************",
    "sourceVer": "dev"
}

相关文章

网友评论

      本文标题:reactnative 使用axios封装网络请求

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