外观
Http 请求
约 1615 字大约 5 分钟
2025-11-30
介绍
组件库内置了基于 luch-request 3.x 的请求实例 http,并从 @/uni_modules/uview-unix 统一导出。你只需要完成一次初始化配置,之后就可以在页面或 api 文件中直接调用 http.get、http.post 等方法。
本文只讲解在组件库中的接入与常用写法,请求取消、上传下载进度、自定义适配器、多实例等更详细的用法请查阅 luch-request 官方文档。
初始化
http 实例从 uni_modules/uview-unix 导出。建议在项目中新建一个统一的请求配置文件,例如 utils/request.ts:
import { http } from '@/uni_modules/uview-unix';
http.setConfig(config => {
config.baseURL = 'https://httpbingo.org';
return config;
});
// 请求拦截
http.interceptors.request.use(
config => {
return config;
},
error => {
return Promise.reject(error);
}
);
// 响应拦截
http.interceptors.response.use(
({ data }) => {
return Promise.resolve(data);
},
({ statusCode, data, errMsg }) => {
if (statusCode == 500) {
return new Promise(() => {});
}
return Promise.reject();
}
);
export default http;然后在 main.uts 中导入一次,确保配置在应用启动时生效:
import App from './App.uvue';
import request from '@/utils/request';
import { createSSRApp } from 'vue';
export function createApp() {
const app = createSSRApp(App);
return {
app
};
}只需要在
main.uts中导入一次,页面里不需要重复导入utils/request.ts。
全局请求配置
可配置项
setConfig 中的 config 与请求时传入的局部配置使用同一套字段。局部配置优先级高于全局配置,header、custom 会与全局值合并,同名时局部覆盖全局。
| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| baseURL | 请求根域名,最终会与 url 拼接 | string | '' |
| header | 请求头,局部与全局合并,同名覆盖 | object | {} |
| method | 请求方法 | string | 'GET' |
| dataType | 返回数据格式 | string | 'json' |
| paramsSerializer | 自定义 params 处理函数 | function | null |
| responseType | 响应类型,支付宝小程序不支持该配置 | string | 'text' |
| custom | 全局自定义参数默认值,可在拦截器中通过 config.custom 读取 | object | {} |
| timeout | 请求超时时间,H5、App、微信小程序、支付宝小程序支持 | number | 60000 |
| sslVerify | 是否验证 ssl 证书,仅 5+ App 安卓端支持 | boolean | true |
| withCredentials | 跨域请求时是否携带凭证(cookies),仅 H5 支持 | boolean | false |
| firstIpv4 | DNS 解析时优先使用 ipv4,仅 App-Android 支持 | boolean | false |
| getTask | 返回当前请求的 task 与 options,可用于取消请求,请勿在回调中修改 options | function | - |
| validateStatus | 自定义状态码验证器,返回 true 表示请求成功 | function | statusCode >= 200 && statusCode < 300 |
| forcedJSONParsing | 是否尝试将响应数据 JSON 化,也可传入 { include: ['UPLOAD', 'DOWNLOAD'] } | boolean | object | true |
全局配置修改 setConfig
setConfig 接收一个回调函数,回调参数为当前全局默认配置,修改后需要把 config 返回:
http.setConfig((config) => {
config.baseURL = 'https://httpbingo.org';
config.timeout = 10000;
config.header = {
...config.header,
'X-Client': 'uview-unix'
};
return config;
});也可以直接修改实例上的 config:
http.config.baseURL = 'https://httpbingo.org';
http.config.header = {
'X-Client': 'uview-unix'
};组件库已内置并导出唯一的
http实例,推荐统一在utils/request.ts中通过setConfig修改全局配置。如果需要多个互不影响的请求实例,请参考官方文档中的new Request({ ... })用法。
直接发起请求
接口名称保持语义化,建议以动词开头,例如 fetchUserInfo、submitLogin、removeArticle:
import { http } from '@/uni_modules/uview-unix';
// 获取用户信息
const fetchUserInfo = (userId: number) => http.get('/anything/user', {
params: {
userId
}
})
// 提交登录
const submitLogin = (account: string, password: string) => http.post('/post', {
account,
password
}, {
header: {
'Content-Type': 'application/json'
}
})
fetchUserInfo(1).then(user => {
console.log('用户信息', user)
})
submitLogin('admin', '123456').then(result => {
console.log('登录结果', result)
})由于响应拦截器已经返回了 data,then 或 await 得到的就是接口响应体,而不是完整的响应对象。
封装 API
推荐把接口统一放到 api 目录(参考 api/common.ts),命名采用「动词 + 资源」的语义化方式,页面只关心业务方法:
import { http } from '@/uni_modules/uview-unix';
// 获取用户信息
export const getUserInfo = (userId: number) => http.get('/anything/user', {
params: {
userId
}
})
// 提交登录
export const submitLogin = (account: string, password: string) => http.post('/post', {
account,
password
}, {
header: {
'Content-Type': 'application/json'
}
})
// 更新用户资料
export const updateUserProfile = (profile: any) => http.put('/put', profile, {
header: {
'Content-Type': 'application/json'
}
})
// 删除文章
export const removeArticle = (articleId: number) => http.delete('/delete', {
articleId
})
// 上传头像
export const uploadAvatar = (filePath: string) => http.upload('/upload', {
filePath,
name: 'avatar'
})页面中使用:
import { getUserInfo, submitLogin } from '@/api/common';
const load = async () => {
const user = await getUserInfo(1);
console.log('用户信息', user);
};
const login = async () => {
const result = await submitLogin('admin', '123456');
console.log('登录结果', result);
};请求方法
| 方法 | 说明 | 示例 |
|---|---|---|
| get | GET 请求 | http.get('/get', { params }) |
| post | POST 请求 | http.post('/post', data) |
| put | PUT 请求 | http.put('/put', data) |
| delete | DELETE 请求 | http.delete('/delete', data) |
| head | HEAD 请求 | http.head('/head', data) |
| upload | 文件上传 | http.upload('/upload', config) |
| download | 文件下载 | http.download('/file') |
| request | 自定义请求,method 必须大写 | http.request({ url, method: 'POST', data }) |
| middleware | 所有请求方式的超集,method 可传 UPLOAD、DOWNLOAD | http.middleware({ url, method: 'UPLOAD' }) |
传参方式
- GET 查询参数放在第二个参数的
params中; - POST、PUT 的请求体直接作为第二个参数传入;
- 请求头、超时时间等放在第三个参数的
header、timeout中。
const data = await http.post('/post', {
name: 'uview-unix',
age: 3
}, {
header: {
'Content-Type': 'application/json',
'X-Token': 'uview-unix'
},
timeout: 10000,
// 自定义参数,可在拦截器中通过 config.custom 读取
custom: {
loading: true
}
});请求时常用的局部配置:
| 参数 | 说明 |
|---|---|
| params | 拼接到 url 上的查询参数 |
| header | 与全局 header 合并,同名覆盖 |
| dataType | 返回数据格式,默认 json |
| timeout | 当前请求的超时时间 |
| custom | 自定义参数,供拦截器等地方使用 |
| getTask | 获取当前请求的 task,可用于取消请求 |
| validateStatus | 当前请求的状态码验证器 |
| forcedJSONParsing | 是否尝试将响应数据 JSON 化 |
请求拦截器
可以在请求发出前统一添加 Token、公共参数或日志:
http.interceptors.request.use(config => {
config.header = {
...config.header,
Authorization: 'Bearer token'
};
return config;
});响应拦截器
当前项目的响应拦截器直接返回 data,因此业务代码拿到的是接口数据:
http.interceptors.response.use(
({ data }) => {
return Promise.resolve(data);
},
error => {
return Promise.reject(error);
}
);如果需要状态码、响应头等完整信息,可以改为返回整个 response,再在业务中按需读取。
上传文件
const result = await http.upload('/upload', {
filePath: tempFilePath,
name: 'file',
formData: {
userId: 1
}
});filePath 可以来自 uni.chooseImage 等选择文件接口。
错误处理
非 2xx 状态码会进入 catch,建议统一提示:
try {
const user = await getUserInfo(1);
console.log(user);
} catch (error) {
uni.showToast({
title: '请求失败,请稍后重试',
icon: 'none'
});
}完整示例
pages/tools/http.uvue 中提供了完整示例,包含:
- GET 查询参数
- POST 表单
- POST JSON
- 自定义请求头
- 404 异常处理
- 延迟请求
- 响应结果格式化与复制
更多功能
以下能力请参考 luch-request 官方文档:
- 请求取消
- 上传进度
- 下载进度
- 自定义适配器
- 多实例配置
- 请求重试
