外观
Http 请求
约 1684 字大约 6 分钟
2025-11-04
该插件适用于普遍的请求场景,支持post、get、put和delete,以及上传下载等请求,有如下特点:
- 基于
Promise对象实现更简单的request使用方式,支持请求和响应拦截 - 支持全局挂载
- 支持多个全局配置实例
- 支持自定义验证器
- 支持文件上传/下载
- 支持task 操作
- 支持多拦截器
- 对参数的处理比
uni.request更强
基本使用
import { http } from '@/uni_modules/uview-unix';
http.request<T>(config) // 通用请求方法,返回值为 Promise,参数T 为响应数据类型
http.get<T>(url[, config]) // GET请求,返回值为 Promise,参数T 为响应数据类型
http.upload<T>(url[, config]) // 上传文件,返回值为 Promise,参数T 为响应数据类型
http.delete<T>(url[, data[, config]]) // DELETE请求,返回值为 Promise,参数T 为响应数据类型
http.head<T>(url[, data[, config]]) // HEAD请求,返回值为 Promise,参数T 为响应数据类型
http.post<T>(url[, data[, config]]) // POST请求,返回值为 Promise,参数T 为响应数据类型
http.put<T>(url[, data[, config]]) // PUT请求,返回值为 Promise,参数T 为响应数据类型
http.connect<T>(url[, data[, config]]) // CONNECT请求,返回值为 Promise,参数T 为响应数据类型
http.options<T>(url[, data[, config]]) // OPTIONS请求,返回值为 Promise,参数T 为响应数据类型全局配置
可选的配置项有如下:
{
baseURL: '',
header: {},
method: 'GET',
dataType: 'json',
responseType: 'json',
timeout: 60000,
sslVerify: true,
withCredentials: false,
firstIpv4: false,
getTask: (task) => {
},
}可以通过http.setConfig()方法进行全局配置,比如配置请求的全局域名baseUrl:
import { http } from '@/uni_modules/uview-unix';
http.setConfig((config) => {
/* config 为默认全局配置*/
config.baseURL = `https://www.example.com`; /* 根域名 */
return config
})GET请求
import { http } from '@/uni_modules/uview-unix';
import type { UnRequestTask } from '@/uni_modules/uview-unix'
const params = {
userName: 'name',
password: '123456',
}
http.get('/user/login', { params: params }).then(res => {
}).catch(err => {
})POST请求
import { http } from '@/uni_modules/uview-unix';
import type { UnRequestTask } from '@/uni_modules/uview-unix'
const formData = {
userName: 'name',
password: '123456',
}
http.post('/user/login', formData).then(res => {
}).catch(err => {
})
// 局部修改配置,局部配置优先级高于全局配置
http.post('/user/login', formData, {
params: {userName: 'name', password: '123456'}, /* 会加在url上 */
header: {}, /* 会与全局header合并,如有同名属性,局部覆盖全局 */
dataType: 'json',
responseType: 'json',
timeout: 60000,
sslVerify: true,
firstIpv4: false,
withCredentials: false,
// 返回当前请求的task
getTask: (task: UnRequestTask) => {
},
}).then(res => {
}).catch(err => {
})UPLOAD请求
具体参数说明:uni.uploadFile
import { http } from '@/uni_modules/uview-unix';
http.upload('api/upload/img', {
// #ifdef H5
files: [], // 需要上传的文件列表。使用 files 时,filePath 和 name 不生效。App、H5( 2.6.15+)
// #endif
fileType: 'image/video/audio', // 仅支付宝小程序,且必填。
filePath: '', // 要上传文件资源的路径。
name: 'file', // 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
timeout: 60000, // H5(HBuilderX 2.9.9+)、APP(HBuilderX 2.9.9+)
header: {}, /* 会与全局header合并,如有同名属性,局部覆盖全局 */
formData: {}, // HTTP 请求中其他额外的 form data
// 返回当前请求的task。请勿在此处修改options。非必填
getTask: (task) => {
// task.onProgressUpdate((res) => {
// console.log('上传进度' + res.progress);
// console.log('已经上传的数据长度' + res.totalBytesSent);
// console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
//
// // 测试条件,取消上传任务。
// if (res.progress > 50) {
// uploadTask.abort();
// }
// });
},
}).then(res => {
// 返回的res.data 已经进行JSON.parse
}).catch(err => {
})DOWNLOAD请求
具体参数说明:uni.downloadFile
import { http } from '@/uni_modules/uview-unix';
http.download('api/download', {
timeout: 3000,
header: {}, /* 会与全局header合并,如有同名属性,局部覆盖全局 */
// 返回当前请求的task。非必填
getTask: (task) => {
// setTimeout(() => {
// task.abort()
// }, 500)
},
}).then(res => {
}).catch(err => {
})请求拦截器
import { http } from '@/uni_modules/uview-unix'
import type { UnRequestFail, UnRequestOptions } from '@/uni_modules/uview-unix'
http.interceptors.request.use((config: UnRequestOptions): any => {
config.header = {
'Authorization': 'Bearer token'
}
config.baseURL = getApiUrl() + getBasePath();
return config
}, (error: UnRequestFail) => {
return Promise.reject(error)
})响应拦截器
import { http } from '@/uni_modules/uview-unix';
import type { UnRequestSuccess, UnRequestFail } from '@/uni_modules/uview-unix'
http.interceptors.response.use((response: UnRequestSuccess): any => {
/* 对响应成功做点什么 可使用async await 做异步操作*/
// if (response.data.code !== 200) { // 服务端返回的状态码不等于200,则reject()
// return Promise.reject(response) // return Promise.reject 可使promise状态进入catch
// if (response.config.custom.verification) { // 演示自定义参数的作用
// return response
// }
return response;
}, (error: UnRequestFail) => {
return Promise.reject(error)
})实践
假设我们项目中需要用到请求和响应拦截器,可按如下步骤进行操作(仅供参考):
1. 全局配置,以及请求,响应拦截器定义
在/utils/request.js中,写入如下内容:
import { http } from '@/uni_modules/uview-unix';
import type { UnRequestSuccess, UnRequestFail, UnRequestOptions } from '@/uni_modules/uview-unix'
// 响应数据类型
type Response = {
code: number, // 业务状态码
data: any, // 实际的业务数据
msg?: string //消息描述
show?: number //是否显示消息
}
// 请求拦截器
http.interceptors.request.use((config: UnRequestOptions): any => {
config.header = {
'Authorization': 'Bearer token'
}
config.baseURL = 'https://httpbin.org';
return config
}, (error: UnRequestFail) => {
return Promise.reject(error)
})
// 响应拦截器
http.interceptors.response.use((response: UnRequestSuccess): any => {
let result: Response = {
code: 0,
data: ''
}
if (response.statusCode == 200) {
result = JSON.parse<Response>(JSON.stringify(response.data))!;
if(result.code == 0){
uni.showToast({
title: result?.msg ?? '请求失败',
icon: 'none'
})
return Promise.reject(result.msg)
}
}
if (response.statusCode == 401) {
uni.navigateTo({
url: '/pages/login/login'
})
return Promise.reject('登录过期,请重新登录')
}
return result.data;
}, (error: UnRequestFail) => {
return Promise.reject(error)
})2. 引用配置
我们可以在main.js中引用/utils/request.js
import { createSSRApp } from 'vue';
import App from './App.vue';
import './common/http.uts'
export function createApp() {
const app = createSSRApp(App);
return {
app
};
}3. Api集中管理
在/api/user.js中编写请求接口:
import { http } from '@/uni_modules/uview-unix';
type Copyright = {
key?: string;
value?: string;
}
type Config = {
domain?: string;
version?: string;
copyright?: Copyright[];
}
// 获取配置信息
export const apiConfig = () => http.get<Config>('/index/config');
// 更新用户信息
export const apiUserUpdate = (data: any) => http.post<any>('/user/update', data);4. 发送请求
import { apiConfig } from '/api/config.js';
import { apiUserUpdate } from '/api/user.js';
//获取配置信息
const getConfig = async ()=> {
const res = await apiConfig();
console.log(res)
}
//获取用户信息
const updateUserUpdate = async ()=> {
const res = await apiUserUpdate({});
console.log(res)
}UnRequestOptions 请求参数
| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| baseURL | 基础URL | String | |
| url | 请求路径 | String | |
| method | 请求方法 | String | GET |
| header | 请求头 | UTSJSONObject | |
| timeout | 超时时间(毫秒) | Number | 30000 |
| withCredentials | 是否跨域请求 | Boolean | false |
| firstIpv4 | 是否使用 IPv4 地址 | Boolean | false |
| enableChunked | 上传文件时是否强制使用 chunked 模式 | Boolean | false |
| dataType | 数据类型 | 'json' | 'text' | 'json' |
| responseType | 响应数据类型 | 'text' | 'json' | 'json' |
| getTask | 获取请求任务 | Function | |
| data | POST请求数据 | any | |
| params | GET请求参数 | UTSJSONObject | |
| name | 文件对应的key(上传文件时) | String | |
| filePath | 要上传文件资源的路径 | String | |
| files | 需要上传的文件列表(App、H5) | UploadFileOptionFiles[] | |
| formData | HTTP请求中其他额外的form data | UTSJSONObject |
UnRequestSuccess 响应成功回调参数
| 参数 | 说明 | 类型 |
|---|---|---|
| data | 响应数据 | any | string |
| statusCode | 状态码 | Number |
| header | 响应头 | any |
| cookies | Cookie列表 | string[] |
| tempFilePath | 临时文件路径(下载文件时) | string |
UnRequestFail 响应失败回调参数
| 参数 | 说明 | 类型 |
|---|---|---|
| errCode | 错误代码 | Number |
| errSubject | 错误主题 | String |
| data | 错误数据 | any |
| cause | 错误原因 | Error |
| errMsg | 错误信息 | String |
UnRequestTask 请求任务
| 参数 | 说明 | 类型 |
|---|---|---|
| task | 请求任务 | UploadTask | DownloadTask | RequestTask |
