React-Native Fetch网络请求的简单封装

import { Alert } from 'react-native';

//export const CTX = 'http://112.74.163.201:8085/zft_app/'; // 需要设置成ip地址,不能设置成localhost
//export const CTX = 'http://192.168.3.110:8061/zft/';
export const CTX = 'http://112.74.163.201:8061/zft/';
//export const CTX='http://47.106.22.165:8085/zft_app/';
export function processError(data) {
    if (data.status === -2) { // 用户未登陆
        navigation.push('Login')
    } else {
        Alert.alert('错误提示', data.msg);
    }
}

export function httpGet(uri) {
    uri = CTX + uri;
    let init = {
        method: 'GET',
        credentials: 'include',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
    };
    return new Promise(function (resolve, reject) {
        fetch(uri, init)
            .then(response => response.json())
            .then(data => {
                if (data.status === 0) {
                    resolve(data);
                } else {
                    processError(data);
                }
            }).catch(function (ex) {
                reject(ex);
                Alert.alert('错误提示', '网络链接出错');
            });
    });
}

export function httpPost(uri, params) {
    uri = CTX + uri;
    let init = {
        method: 'POST',
        credentials: 'include',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(params)
    };
    return new Promise(function (resolve, reject) {
        fetch(uri, init)
            .then(response => response.json())
            .then(data => {
                if (data.status === 0) {
                    resolve(data);
                } else {
                    processError(data);
                }
            }).catch(function (ex) {
                reject(ex);
                Alert.alert('错误提示', '网络链接出错');
            });
    });
}

export function httpUpload(uri, params) {
    uri = CTX + uri;
    let init = {
        method: 'POST',
        credentials: 'include',
        headers: {
            'Content-Type': 'multipart/form-data',
        },
        body: params
    };
    return new Promise(function (resolve, reject) {
        fetch(uri, init)
            .then(response => response.json())
            .then(data => {
                if (data.status === 0) {
                    resolve(data);
                } else {
                    processError(data);
                }
            }).catch(function (ex) {
                reject(ex);
                Alert.alert('错误提示', '网络链接出错');
            });
    });
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值