react native的网络请求推荐使用axios和fetch 两种方式,当前阐述的是axios
1.安装axios
yarn add react-native-axios
2.创建一个js,进行基本的配置
let instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'}
withCredentials:true });
baseURL:设置相对应的baseURL来传递URL
timeout:设置超时
withCredentials: 允许cookie
Headers:设置头部信息
method:设置请求方式(常见的有get,post,put,patch,delect)
responseType:设置接受的类型
3.拦截器
instance.interceptors.request.use(function (config) { const secretKey = getSecretKey() if (secretKey) { // 登录之后 store.getters.token config.headers['secret-key'] = secretKey } else { config.headers['action-key'] = getExternalKey() } return config }, function (error) { return Promise.reject(error); }); let alert = false; // 响应 instance.interceptors.response.use(response => { // 根据状态码做相应的事情 const res = response.data if (res.code === 1 && res.showMsg === true) { // 成功 showToast(res.message,1500); } if (res.code === -2 && res.showMsg === true) { // 错误 showToast(res.message,3000); } if (res.code === 2) { // 警告 showToast(res.message,3000); } if (res.code === 1003) { // 权限不足 的情况 showToast('账号权限不足!',2500); } if (res.code === 1004 && !alert) { // 获取不到用户信息 或 登录错误 alert = true showToast('登录失败!',2500); } console.log(res); return res }, (error) => { showToast('出错了!请稍后再试!',5000); return Promise.reject(error); })
注:在react native IOS版本下无toast,自己手动安装
yarn add react-native-easy-toast