这里是用 基于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}`) }
原文:https://www.cnblogs.com/hai-cheng/p/8992071.html