React native
React Native 提供了和 web 标准一致的Fetch API,用于满足开发者访问网络的需求,下面提供直接封装一个网络请求。
新建一个FetchManager.js文件,内容如下
import {
Alert,
ToastAndroid,
NativeModules
} from 'react-native'
export default class FetchManager {
/** * GET 请求 */
static get(url, params, success, fail, error) {
if (params) {
let paramsArray = [];
//拼接参数
Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
if (url.search(/\?/) === -1) {
url += '?' + paramsArray.join('&')
} else {
url += '&' + paramsArray.join('&')
}
}
fetch(url, {
headers: {
//看后台需求决定配置参数,例如我们后台要求将appId放在这里请求
// appId: '1234345656'
},
})
.then(response => response.json())
//把response转为json
.then(responseJson => {
// 拿到上面的转好的json
//根据实际的请求回来格式来处理回调
if (responseJson['success'] === true) {
// 0为请求成功
success && success(responseJson)
} else {
fail && fail(responseJson)
//可以处理返回的错误信息
}
}).catch(e => {
console.log(e)
error && error(e)
})
}
/** * POST 请求,经测试用FormData传递数据也可以 ,支持跨域与CooKie传递*/
static post(url, formData, success, fail, error) {
fetch(url, {
credentials: 'include',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
// 'Content-Type': 'application/x-www-form-urlencoded'
// 'Cookie': ''
},
mode: "cors",
body: formData
}).then(response => response.json())
//把response转为json
.then(responseJson => {
// 拿到上面的转好的json
//根据实际的请求回来格式来处理回调
if (responseJson['success'] === true) {
// 0为请求成功
success && success(responseJson)
} else {
fail && fail(responseJson)
//可以处理返回的错误信息
}
}).catch(e => {
console.log(e)
error && error(e)
})
}
/** * POST 请求,经测试用FormData传递数据也可以 Json格式 */
static postJson(url, params, success, fail, error) {
fetch(url, {
credentials: 'include',
method: 'POST',
headers: {
'Accept': '*/*',
//媒体格式类型key/value格式
// 'Accept': 'application/json;charset=UTF-8',
'Content-Type': 'application/json;charset=UTF-8'
},
//mode:"cors",
body: JSON.stringify(params)
}).then(response => response.json())
//把response转为json
.then(responseJson => {
// 拿到上面的转好的json
//根据实际的请求回来格式来处理回调
if (responseJson['success'] === true) {
// 0为请求成功
success && success(responseJson)
} else {
fail && fail(responseJson)
//可以处理返回的错误信息
}
}).catch(e => {
console.log(e)
error && error(e)
ToastUtil.show("请检查您的网络是否已经连接");
})
}
/** * @images uri数组 * @param FormData格式,没有参数的话传null */
static uploadFile(url, images, params, success, fail, error) {
let formData = new FormData();
if (params) {
formData = params;
}
for (let i = 0; i < images.length; i++) {
let uri = images[i]
let date = new Date()
let name = date.getTime() + '.png'
//用时间戳保证名字的唯一性
let file = {
uri: uri,
type: 'multipart/form-data',
name: name
}
formData.append('file', file)
}
fetch(url, {
method: 'POST', headers: {
'Accept': 'application/json',
//媒体格式类型key/value格式
'Content-Type': 'multipart/form-data',
// customerId: customerId,
// appId: appId
}, body: formData
}).then(response => response.json())
//把response转为json
.then(responseJson => {
// 拿到上面的转好的json
//根据实际的请求回来格式来处理回调
if (responseJson['success'] === true) {
// 0为请求成功
success && success(responseJson)
} else {
fail && fail(responseJson)
//可以处理返回的错误信息
}
}).catch(e => {
console.log(e)
error && error(e)
})
}
}
使用步骤
在其他js文件内直接调用
import React from 'react';
import FetchManager from './FetchManager'
export class Test extends React.Component {
componentDidMount(): void {
let url = '填上你的请求url地址';
let formData = new FormData();
formData.append("id", 'id');
FetchManager.post(url, formData, (json) => {
//TODO成功回调
}, (json) => {
//TODO失败回调
}, (e) => {
//TODO错误回调
});
}
render(): React.ReactNode {
return (
<View>
<Text>测试</Text>
</View>
);
}
结语
欢迎大家拍砖点赞分析收藏,谢谢大家。