用ts简单封装一个RN端的fetch请求,主要有三个文件:
1、ServiceConfig.ts主要是一些服务器的配置
const SERVICEURL = 'https://www.baidu.com';
export { SERVICEURL }
const baseUrl='/app/v2.0.0/'
const uploadUrl=baseUrl+'uploadFile'
const auth = {
signUp: baseUrl+'register',
signIn: baseUrl+'login',
logOut: baseUrl+'logout',
loginByAuthCode: baseUrl+'loginByAuthCode',
getSMS: baseUrl+'sendAuthCode',
refreshToken: baseUrl+'refreshToken',
}
export {
auth,
uploadUrl
}
2、FetchData.ts Post和Get请求方法
import { SERVICEURL } from './ServiceConfig'
//post get请求
export function fetchData(url: string, params: object, method: string = 'POST') {
const abortable_promise = Promise.race([
getTimeOutPromise(),
getFetchPromise(url, params,method)
])
return abortable_promise
}
//超时
function getTimeOutPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('network time out'))
}, __DEV__ ? 10000 : 10000)
})
}
//post get
function getFetchPromise(url: string, params: object, method: string) {
const header = {
'User-Agent': '',
'Content-Type': 'application/json;charset=UTF-8',
'Accept': 'application/json'
}
let reqUrl = ''
if (method === 'GET') {
if (params) {
let paramsArray: any = []
Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
if (url.search(/\?/) === -1) {
url += '?' + paramsArray.join('&')
} else {
url += '&' + paramsArray.join('&')
}
}
reqUrl = SERVICEURL + url
if (__DEV__) {
console.log('请求的url==' + reqUrl)
}
return fetch(reqUrl, {
method: method,
headers: header,
}).then((response) => {
if (response.ok) {
return response.json
} else {
throw new Error('network error')
}
}).then((model) => {
return model
}).catch((error) => {
console.log(error);
})
} else {
reqUrl = SERVICEURL + url
if (__DEV__) {
console.log('请求的url==' + reqUrl)
console.log('params==' + JSON.stringify(params));
}
return fetch(reqUrl, {
method: method,
body: JSON.stringify(params),
headers: header,
}).then((response) => {
if (response.ok) {
return response.json
} else {
throw new Error('network error')
}
}).then((model) => {
return model
}).catch((error) => {
console.log(error);
})
}
}
//上传图片的POST请求
export function fetchDataPost(url, params: object) {
//create header
const header = {
'User-Agent': '',
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
}
//create formData
let formData = new FormData();
const keys = Object.keys(params)
keys.forEach((key) => {
formData.append(key, params[key])
})
const reqUrl=SERVICEURL+url
return fetch(reqUrl, {
method: 'POST',
body: formData,
headers: header,
}).then((response) => {
if (response.ok) {
return response.json
} else {
throw new Error('network error')
}
}).then((model) => {
return model
}).catch((error) => {
console.log(error);
})
}
3、Api.ts 接口调用
import {fetchData,fetchDataPost} from './FetchData'
import {auth,uploadUrl} from './ServiceConfig'
//登录
export function login(userName: string, password: string) {
return fetchData(auth.signIn, {
username: userName,
password: password,
})
}
//上传图片接口
export async function uploadImageWithPost(filePath:string) {
const userId = '111'
const fetchPromise = await uploadFile(filePath, userId)
.then((model) => {
return model
}).catch((error) => {
throw error
})
return fetchPromise
}
export function uploadFile(filePath: string, name: string) {
let file = { uri: filePath, type: 'multipart/form-data', name: `${name}.jpg` };
return fetchDataPost(uploadUrl, {
file: file,
})
}