首页 > 其他 > 详细

react-native 请求封装

时间:2018-05-04 18:55:20      阅读:520      评论:0      收藏:0      [点我收藏+]

这里是用 基于ES6  promise 的 axios 插件 ,当然需要先下载此插件

npm install axios

1,首先在跟目录创建 http 文件夹 并在里边创建 index.js 代码如下:

import React, { Component } from ‘react‘;
import axios from ‘axios‘

let token = ‘‘;

var instance = axios.create({
    baseURL: ‘https://baidu.com‘,
    timeout: 5000,
    headers: {‘X-Custom-Header‘: ‘foobar‘},
     // `transformResponse` allows changes to the response data to be made before
    // it is passed to then/catch
    transformResponse: [function (data) {
        /**
         * 通过返回的data,来统一处理异常
         */
        return data;
        // Alter defaults after instance has been created 处理token
        instance.defaults.headers.common[‘Authorization‘] = token;    
    }],
});

export default instance;

2,在需要使用 使用请求的页面方法如下:

import axios from ‘../http‘   //引入上边的index文件
  // this.props.navigation.navigate(‘Page4‘,params);  具体请求方法
        axios.get(‘/api/cms/eleser/homePage‘)
            .then(res => {
                console.log(res);
            }), err => {
                console.log(`${err}`)
            }

 

react-native 请求封装

原文:https://www.cnblogs.com/hai-cheng/p/8992071.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!