# Http请求
该插件适用于普遍的请求场景,支持post、get、put和delete,以及上传下载等请求,有如下特点:
- 基于
Promise对象实现更简单的request使用方式,支持请求和响应拦截 - 支持全局挂载
- 支持多个全局配置实例
- 支持自定义验证器
- 支持文件上传/下载
- 支持task 操作
- 支持多拦截器
- 对参数的处理比
uni.request更强
# 基本使用
api.js
import { http } from '@/uni_modules/uview-unix'; http.request(config) http.get(url[, config]) http.upload(url[, config]) http.delete(url[, data[, config]]) http.head(url[, data[, config]]) http.post(url[, data[, config]]) http.put(url[, data[, config]]) http.connect(url[, data[, config]]) http.options(url[, data[, config]])✅ Copy success!
# 全局配置
可选的配置项有如下:
{ baseURL: '', header: {}, method: 'GET', dataType: 'json', responseType: 'text', timeout: 60000, sslVerify: true, withCredentials: false, firstIpv4: false, // DNS解析时优先使用ipv4 仅 App-Android 支持 (HBuilderX 2.8.0+) // 局部优先级高于全局,返回当前请求的task getTask: (task) => { // 相当于设置了请求超时时间500ms setTimeout(() => { task.abort() }, 500) }, }✅ Copy success!
可以通过http.setConfig()方法进行全局配置,比如配置请求的全局域名baseUrl:
import { http } from '@/uni_modules/uview-unix'; http.setConfig((config) => { /* config 为默认全局配置*/ config.baseURL = `https://www.example.com`; /* 根域名 */ return config })✅ Copy success!
# GET请求
需要注意的是,get请求与post请求略有不同,get请求所有参数都在方法的第二个参数中,而post请求的第二个参数为请求参数params,而第三个参数才为配置项。
import { http } from '@/uni_modules/uview-unix'; import type { UnRequestTask } from '@/uni_modules/uview-unix' // 基本用法,注意:get请求的参数以及配置项都在第二个参数中 http.get('/user/login', {params: {userName: 'name', password: '123456'}}).then(res => { }).catch(err => { }) // 局部修改配置,局部配置优先级高于全局配置 http.get('/user/login', { params: {userName: 'name', password: '123456'}, /* 会加在url上 */ header: {}, /* 会与全局header合并,如有同名属性,局部覆盖全局 */ dataType: 'json', responseType: 'json', timeout: 60000, sslVerify: true, firstIpv4: false, withCredentials: false, // 返回当前请求的task getTask: (task: UnRequestTask) => { // 相当于设置超时时间500ms // setTimeout(() => { // task.abort() // }, 500) }, }).then(res => { }).catch(err => { })✅ Copy success!
# POST请求
需要注意的是,get请求与post请求略有不同,get请求所有参数都在方法的第二个参数中,而post请求的第二个参数为请求参数params,而第三个参数才为配置项。
import { http } from '@/uni_modules/uview-unix'; import type { UnRequestTask } from '@/uni_modules/uview-unix' // 基本用法,注意:post的第三个参数才为配置项 http.post('/user/login', {userName: 'name', password: '123456'} ).then(res => { }).catch(err => { }) // 局部修改配置,局部配置优先级高于全局配置 http.post('/user/login', {userName: 'name', password: '123456'}, { params: {userName: 'name', password: '123456'}, /* 会加在url上 */ header: {}, /* 会与全局header合并,如有同名属性,局部覆盖全局 */ dataType: 'json', responseType: 'json', timeout: 60000, sslVerify: true, firstIpv4: false, withCredentials: false, // 返回当前请求的task getTask: (task: UnRequestTask) => { // 相当于设置超时时间500ms // setTimeout(() => { // task.abort() // }, 500) }, }).then(res => { }).catch(err => { })✅ Copy success!
# UPLOAD请求
具体参数说明:uni.uploadFile (opens new window)
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 => { })✅ Copy success!
# DOWNLOAD请求
具体参数说明:uni.downloadFile (opens new window)
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 => { })✅ Copy success!
# 请求拦截器
import { http } from '@/uni_modules/uview-unix' import type { UnRequestSuccess, UnRequestOptions } from '@/uni_modules/uview-unix' http.interceptors.request.use((config): UnRequestOptions => { // 可使用async await 做异步操作 config.header = { ...config.header, a: 1 // 演示拦截器header加参 } // 演示 // if (!token) { // 如果token不存在,return Promise.reject(config) 会取消本次请求 // return Promise.reject(config) // } return config }, config => { // 可使用async await 做异步操作 return Promise.reject(config) })✅ Copy success!
# 响应拦截器
import { http } from '@/uni_modules/uview-unix'; import type { UnRequestSuccess, UnRequestOptions } from '@/uni_modules/uview-unix' http.interceptors.response.use((response): UnRequestSuccess => { /* 对响应成功做点什么 可使用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.data // } console.log(response) return response }, (response) => { /* 对响应错误做点什么 (statusCode !== 200)*/ console.log(response) return Promise.reject(response) })✅ Copy success!
# 实践
假设我们项目中需要用到请求和响应拦截器,可按如下步骤进行操作(仅供参考):
# 1. 全局配置,以及请求,响应拦截器定义
在/utils/request.js中,写入如下内容:
request.js
import { http } from '@/uni_modules/uview-unix'; import type { UnRequestSuccess, UnRequestOptions } from '@/uni_modules/uview-unix' http.interceptors.request.use((config): UnRequestOptions => { config.header = { 'Authorization': 'Bearer token' } config.baseURL = 'https://httpbin.org'; return config }, config => { return Promise.reject(config) }) http.interceptors.response.use((response): UnRequestSuccess => { return response.data }, config => { return Promise.reject(config) })✅ Copy success!
# 2. 引用配置
我们可以在main.js中引用/utils/request.js
main.js
import { createSSRApp } from 'vue'; import App from './App.vue'; import './common/http.uts' export function createApp() { const app = createSSRApp(App); return { app }; }✅ Copy success!
# 3. Api集中管理
在/api/user.js中编写请求接口:
user.js
import { http } from '@/uni_modules/uview-unix'; // 手机号登录 export const apiLogin = (params: any) => http.post('/weapp/login', params); // 退出登录 export const apiLogout = () => http.post('/weapp/login/logout'); // 获取用户信息 export const apiUserProfile = (params: any) => http.get('/weapp/user/profile', params); // 更新用户信息 export const apiUserUpdate = (params: any) => http.post('/weapp/user/update', params);✅ Copy success!
# 4. 发送请求
import { apiUserProfile } from '/api/user.js'; //获取用户信息 const getUserProfile = async ()=> { const res = await apiUserProfile(); console.log(res) }✅ Copy success!
# 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 | 获取请求任务 | (task: UnRequestTask) => void | |
| 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 |