Request 网络请求 VIP专属 V1.3.0+

概述

Request 网络请求,支持Promise,可在发起请求和请求响应之前进行拦截。

# 支持平台

目前开发小程序与H5推荐使用 FirstUI nvue版本 (opens new window)

安卓系统版本 安卓uni-app 安卓uniapp-x iOS系统版本 iOS uniapp iOS uniapp-x 小程序 H5/Web
5.0 × 9.0 × ×

# 引入

在根目录main.uts中全局引入
import { firstuiRequest } from './components/firstui/fui-request/index.uts'
import { FuiRequestConfigParam } from './components/firstui/fui-request/types/index.uts'

// 实例化类对象
const http = firstuiRequest()

//初始化请求配置项
http.create({
	host: 'https://ffa.firstui.cn',
	// loadingText:'加载中',
	header: {
		// 'content-type': 'application/x-www-form-urlencoded'
	}
} as FuiRequestConfigParam)

//请求拦截
http.useRequestInterceptors((config : FuiRequestConfigParam) : FuiRequestConfigParam => {
	//请求之前可在请求头中加入token等信息
	const token = uni.getStorageSync('firstui_token');
	if (config.header != null) {
		(config.header as UTSJSONObject)['Authorization'] = token
	} else {
		config.header = {
			'Authorization': token
		} as UTSJSONObject
	}
	return config
})

//响应拦截
http.useResponseInterceptors((response : RequestSuccess<any>) : RequestSuccess<any> => {
	//TODO
	return response
}, (err : any) : any => {
	//错误响应:断网、错误域名等
	return err;
})

export function createApp() {
	const app = createSSRApp(App);
	//以下代码需要开发工具升级至 Hbuilder x 3.9.9+ (正式版本如果没有则下载alpha版本)
	app.use(function (app) {
		app.config.globalProperties.http = http;
	});
	return {
		app
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

# 代码演示

部分示例演示,完整使用请参考示例程序以及文档API。
GET请求

通过 data 传入接口所需参数。

//配置参数类型
import { FuiRequestConfigParam } from '@/components/firstui/fui-request/types/index.uts'

//发起请求
this.http.get('/api/example/info', {
	data: {
		id: 1
	}
} as FuiRequestConfigParam).then((response : any) => {
	console.log(response)
	const res = JSON.parse(JSON.stringify(response)) as UTSJSONObject
	const d = res['data'] as UTSJSONObject;
	const succeeded = d['succeeded'] as boolean;
	if (succeeded) {
		console.log('请求成功!')
	}
}).catch((e: any | null) => {
	console.log(e)
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
POST请求

通过 data 传入接口所需参数,brief 参数控制是否返回简洁数据,为true返回数据则不包含请求头等信息。

//配置参数类型
import { FuiRequestConfigParam } from '@/components/firstui/fui-request/types/index.uts'

//发起请求
post() {
	this.http.post('/api/example/info', {
		brief: true,
		data: {
			Id: 2,
			Name: '张三'
		}
	} as FuiRequestConfigParam).then((response : any) => {
		console.log(response)
		const res = JSON.parse(JSON.stringify(response)) as UTSJSONObject
		const succeeded = res['succeeded'] as boolean;
		if (succeeded) {
			console.log('请求成功!')
		}
	}).catch((e: any | null) => {
		console.log(e)
	})
},
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
自定义接口域名

通过 host 参数修改默认接口域名,只对本次请求有效。

//配置参数类型
import { FuiRequestConfigParam } from '@/components/firstui/fui-request/types/index.uts'

//发起请求
changeHost() {
	this.http.get('/api/example/info', {
		//接口域名
		host: 'https://ffa.firstui.cn'
	} as FuiRequestConfigParam).then((response : any) => {
		console.log(response)
		const res = JSON.parse(JSON.stringify(response)) as UTSJSONObject
		const d = res['data'] as UTSJSONObject;
		const succeeded = d['succeeded'] as boolean;
		if (succeeded) {
			console.log('请求成功!')
		}
	}).catch((e: any | null) => {
		console.log(e)
	})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
合并多个请求

全部返回数据后再进行其他操作。

//配置参数类型
import { FuiRequestConfigParam } from '@/components/firstui/fui-request/types/index.uts'

//发起请求
all() {
	//合并多个请求:都返回数据后再进行其他操作
	let func1 = this.http.get('/api/example/info')
	let func2 = this.http.get('/api/example/info', {
		data: {
			id: 3
		}
	} as FuiRequestConfigParam)
	this.http.all([func1, func2]).then((response : any) => {
		console.log(response)
		console.log('请求成功!')
	}).catch((e: any | null) => {
		console.log(e)
	})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
同步请求

异步转同步,等待请求结束再执行其他操作。

async sync() : Promise<void> {
	console.log('同步请求start...')
	let response = await this.http.get('/api/example/info')
	console.log(response)
	console.log('同步请求end...')
}
1
2
3
4
5
6
request方法请求

支持多种请求方式,method 有效值必须大写,有效值:"GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS"。

//配置参数类型
import { FuiRequestConfigParam } from '@/components/firstui/fui-request/types/index.uts'

//发起请求
request() {
	this.http.request({
		url: '/api/example/info',
		method: 'GET',
		data: {
			id: '100'
		}
	} as FuiRequestConfigParam).then((response : any) => {
		const res = JSON.parse(JSON.stringify(response)) as UTSJSONObject
		const d = res['data'] as UTSJSONObject;
		const succeeded = d['succeeded'] as boolean;
		if (succeeded) {
			console.log('请求成功!')
		}
	}).catch((e: any | null) => { 
		console.log(e)
	})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

TIP

请求返回的数据类型目前都为any,需自行根据服务端返回数据进行转化使用。

# Methods

方法名 说明 传入参数
useRequestInterceptors 请求拦截 fulfilled : FuiRequestInterceptor
ejectRequestInterceptors 移除请求拦截 key : FuiRequestInterceptorParam
useResponseInterceptors 响应拦截 fulfilled : FuiResponseInterceptor, rejected : FuiRejectedInterceptor
ejectResponseInterceptors 移除响应拦截 key : FuiResponseInterceptorParam
create 初始化配置项 config : FuiRequestConfigParam
request request请求,可以发起平台支持的请求方式,GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS等 config : FuiRequestConfigParam
get get请求 url,config
post post请求 url,config
put put请求 url,config
delete delete请求 url,config
all 合并请求 requests:Promise<any>[]
abort 中断请求,请求长时间未响应时可手动中断请求 cancelToken:详见FuiRequestConfigParam 类型中说明
//方法详细说明

/**
* 设置请求拦截
* @description 设置请求拦截,处理请求配置参数
* @param {Function} fulfilled {FuiRequestInterceptor} 请求拦截 fulfilled 方法【配置参数(config)处理方法】
*/
useRequestInterceptors(fulfilled : FuiRequestInterceptor)

/**
* 移除请求拦截
* @description 移除请求拦截
* @param {Object} key {FuiRequestInterceptorParam} 请求拦截器参数
*/
ejectRequestInterceptors(key : FuiRequestInterceptorParam)

/**
* 设置响应拦截
* @description 设置请求拦截,处理请求配置参数
* @param {Function} fulfilled {FuiResponseInterceptor} 响应数据处理方法
* @param {Function} rejected {FuiRejectedInterceptor} 出错时处理方法
*/
useResponseInterceptors(fulfilled : FuiResponseInterceptor, rejected : FuiRejectedInterceptor)

/**
* 移除响应拦截
* @description 移除响应拦截
* @param {Object} key {FuiResponseInterceptorParam} 响应拦截器参数
*/
ejectResponseInterceptors(key : FuiResponseInterceptorParam)

/**
* 初始化配置参数
* @description 初始化配置参数,如接口域名,请求头等
* @param {Object} config {FuiRequestConfigParam} 配置参数
*/
create(config : FuiRequestConfigParam)

/**
* request请求
* @description request请求
* @param {Object} config {FuiRequestConfigParam} 配置参数
* @returns {Promise<any>} Promise&lt;any&gt;
*/
request(config : FuiRequestConfigParam) : Promise<any>

/**
* get请求
* @description get请求
* @param url 请求地址
* @param {Object} config {FuiRequestConfigParam} 配置参数
* @returns {Promise<any>} Promise&lt;any&gt;
*/
get(url : string = '', config : FuiRequestConfigParam = {} as FuiRequestConfigParam) : Promise<any>

/**
* post请求
* @description post请求
* @param url 请求地址
* @param {Object} config {FuiRequestConfigParam} 配置参数
* @returns {Promise<any>} Promise&lt;any&gt;
*/
post(url : string = '', config : FuiRequestConfigParam = {} as FuiRequestConfigParam) : Promise<any>

/**
* put请求
* @description put请求
* @param url 请求地址
* @param {Object} config {FuiRequestConfigParam} 配置参数
* @returns {Promise<any>} Promise&lt;any&gt;
*/
put(url : string = '', config : FuiRequestConfigParam = {} as FuiRequestConfigParam) : Promise<any>

/**
* delete请求
* @description delete请求
* @param url 请求地址
* @param {Object} config {FuiRequestConfigParam} 配置参数
* @returns {Promise<any>} Promise&lt;any&gt;
*/
delete(url : string = '', config : FuiRequestConfigParam = {} as FuiRequestConfigParam) : Promise<any>

/**
* 批量请求
* @description 批量请求
* @param {Array} requests {Promise&lt;any&gt;[]} 请求集合
* @returns {Promise<any[]>} Promise&lt;any[]&gt;
*/
all(requests : Promise<any>[]) : Promise<any[]>

/**
* 中断请求
* @description 中断请求
* @param {string} cancelToken {string} 请求标记,用于中断该请求,不同请求不可重复,只可包含数字、字母、下划线,如:firstui_001
*/
abort(cancelToken : string)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96

# 参数类型

位置:fui-request/types/index.uts

/*!
* fui-request:参数类型
*
* 官网地址:https://firstui.cn/
* 文档地址:https://unix.firstui.cn/
*/

/**
* 配置参数类型
* @description 配置config参数类型
* @param {string} host {string} 接口域名,如:https://firstui.cn(如果host为空,则直接使用传入的目标地址url)
* @param {string} url {string}  接口地址:/order/getList(如果host为空,直接传入:https://firstui.cn/order/getList)
* @param {any | null} data {UTSJSONObject | string}  请求参数
* @param {UTSJSONObject} header {UTSJSONObject}  请求头
* @param {string} method {string}  请求方式
* @param {number} timeout {number}  超时时间ms,大于2000时才生效,否则使用全局配置或者默认值
* @param {string} dataType {string}  
* @param {boolean} prevent {boolean}  是否阻止拦截重复的请求(重复:请求地址url + method + 参数data 一致)
* @param {string[]} keys {string[]}   Array<String> 参数data中的key,prevent为true时有效,进行重复请求判断时移除keys中相关参数,如时间戳、随机数等.
* @param {boolean} brief {boolean}  是否仅返回简要数据:true-仅返回接口数据data,false-返回包含header、statusCode、errMsg、data等数据
* @param {string} cancelToken {string}  String 请求标记,用于中断该请求,不同请求不可重复,只可包含数字、字母、下划线,如:firstui_001
* @param {boolean} showLoading {boolean}  是否显示loading
* @param {string} loadingText {string}  加载中提示文本,showLoading为true时有效
* @param {string} errorMsg {string}  出错提示文本
* @param {boolean} firstIpv4 {boolean}  DNS解析时优先使用ipv4
* @param {boolean} withCredentials {boolean}  跨域请求时是否携带凭证(cookies)
* @param {string} arrayFormat {string}  get请求时参数值为数组时处理方式,可选值:comma-值逗号拼接,repeat-重复参数名,brackets-带中括号参数名,indices-数组下标参数名
*/
export type FuiRequestConfigParam = {
	host ?: string;
	url ?: string;
	data ?: any;
	header ?: UTSJSONObject;
	method ?: RequestMethod | null;
	timeout ?: number;
	dataType ?: string;
	prevent ?: boolean;
	keys ?: string[];
	brief ?: boolean;
	cancelToken ?: string;
	showLoading ?: boolean;
	loadingText ?: string;
	errorMsg ?: string;
	firstIpv4 ?: boolean | null;
	withCredentials ?: boolean | null;
	arrayFormat ?: string;
}

/**
 * 请求拦截 fulfilled 方法类型
 * @description FuiRequestInterceptor = (config : FuiRequestConfigParam) => FuiRequestConfigParam;
*/
export type FuiRequestInterceptor = (config : FuiRequestConfigParam) => FuiRequestConfigParam;

/**
 * 响应拦截 fulfilled 方法类型
 * @description FuiResponseInterceptor = (response : any) => any
*/

export type FuiResponseInterceptor = (response : RequestSuccess<any>) => RequestSuccess<any>;
/**
 * 请求拦截 / 响应拦截 rejected 方法类型
 * @description FuiRejectedInterceptor = (err : any) => any
*/

export type FuiRejectedInterceptor = (err : any) => any;

/**
 * 请求拦截器
*/
export type FuiRequestInterceptorParam = {
	fulfilled : FuiRequestInterceptor;
	rejected ?: FuiRejectedInterceptor;
}

/**
 * 响应拦截器
*/
export type FuiResponseInterceptorParam = {
	fulfilled : FuiResponseInterceptor;
	rejected ?: FuiRejectedInterceptor;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Config配置参数 arrayFormat 不同值输出参数示例 :

1、arrayFormat: 'indices'
-- 参数 {a:['b', 'c']} 输出结果:'a[0]=b&a[1]=c'

2、arrayFormat: 'brackets'
-- 参数 {a:['b', 'c']} 输出结果:'a[]=b&a[]=c'

3、arrayFormat: 'repeat'
-- 参数 {a:['b', 'c']} 输出结果:'a=b&a=c'

4、arrayFormat: 'comma' (默认使用此方式)
-- 参数 {a:['b', 'c']} 输出结果:'a=b,c'

1
2
3
4
5
6
7
8
9
10
11
12
13
14

示例预览

# 示例代码地址

VIP内容代码请查看订单页下载的组件库示例源码。

# 特别说明

该组件为付费组件,UNI-APP unix版VIP用户可免费使用 。

开通会员 (opens new window)

Last Updated: 4/8/2024, 10:57:29 PM