1.新建Fetch.tsx(作者采用的是TypeScript)
import _ from 'lodash'
import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'
import {Toast} from "antd-mobile-rn"
import {DeviceEventEmitter} from 'react-native'
import config from "./config";
interface ajaxOptions {
baseURL?: string
version?: string
headers?: object
method?: string
data?: object
}
export const ajax = (url: string, options: ajaxOptions) => {
let axiosOptions: AxiosRequestConfig = {}
axiosOptions.baseURL = config.host
axiosOptions.headers = {
//無請求頭可忽略
Authorization:'BasicAuth ' + config.ticket,
...options.headers
}
//請求方式
axiosOptions.method = options.method || 'get'
//超時時間
axiosOptions.timeout = 30 * 1000
if (options.data && _.includes(['get', 'delete'], options.method))
axiosOptions.params = options.data
else
axiosOptions.data = options.data
return new Promise<AJAXErrorResult>((resolve:any, reject:any) => {
axios(url, axiosOptions)
.then(async (res: AxiosResponse<ServerResponseData>) => {
if(res.data.status === 1){
resolve(res.data)
return
// @ts-ignore
} else if (res.data.Status === 1) {
resolve(res.data)
return
}
Toast.fail(res.data.error)
reject({
...res,
handled:false
})
})
.catch(async (err: AxiosError) => {
console.warn(err)
console.log(url,axiosOptions)
if (!err.response) {
Toast.fail('服務繁忙辉巡,稍候請重試')
reject({ ...err, handled: true })
return
}
if (err.response.status == 401) {
reject({ handled: true })
Toast.info('登錄狀態(tài)失效钟鸵,請重新登錄')
DeviceEventEmitter.emit('LogoutEvent',null )
}
else if (err.response.status == 400) {
reject({
data: err.response.data,
message: _.get(err.response.data, 'msg'),
handled: false
})
}
else {
reject({ ...err, handled: true })
Toast.fail('服務繁忙,稍候請重試')
}
})
})
}
export const GET = (url: string, options: ajaxOptions) => ajax(url, {
...options,
method: 'get'
})
export const PUT = (url: string, options: ajaxOptions) => ajax(url, {
...options,
method: 'put'
})
export const POST = (url: string, options: ajaxOptions) => ajax(url, {
...options,
method: 'post'
})
export const DEL = (url: string, options: ajaxOptions) => ajax(url, {
...options,
method: 'delete'
})
2.創(chuàng)建RequestHelper.ts
//引用
import { POST, GET, PUT, DEL } from "./Fetch";
// 獲取驗證碼
export function requestForValidCode() {
return GET('/api/User/GetValidateNumKey', {})
}
// 登錄
export function requestForlogin(params: FormLoginModel) {
return POST('Api/User/UserLogin', {
data: {
...params
}
})
}
3.使用RequestHelper
requestForlogin({
LoginName: phoneStr,
LoginPass: password
})
.then((res: any) => {
})
.catch((err: any) => {
if (!err.data.handled) {
}
})
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者