囊垦判浪一、概述uni-app x 提供了 uni.request() 方法。uni.request({url: https://api.example.com,method: GET})在实际项目开发中直接使用 uni.request 会带来诸多问题例如重复代码多如每次都要写 baseURL错误处理分散难以统一管理缺乏请求/响应拦截能力Token 注入繁琐Loading 状态管理混乱为了解决这些问题封装一个统一的 HTTP 请求库是企业级开发的最佳实践。二、封装requestuview-plus 自带一个 http 模块但是在实际项目中还是要自己封装一个统一管理。在项目根目录创建utils目录在里面创建request.ts。 注意文件后缀必须是ts而不是js复制代码// utils/request.tsimport { http } from uview-plus/* 1. 全局配置 */http.setConfig((config) {config.baseURL https://api.example.com // api地址config.timeout 8000 // 单位毫秒对应8秒config.loadingText 加载中...config.loading true // 开启 loading 动画return config})/* 2. 请求拦截 */http.interceptors.request.use((config) {const token uni.getStorageSync(token)if (token) config.header.Authorization Bearer ${token}return config})/* 3. 响应拦截 */http.interceptors.response.use((response) response.data,(err) {// ?? 强制断言让 UTS 闭嘴(uni as any).$u.toast(err.message || 网络错误)return Promise.reject(err)})export default http复制代码修改 main.uts引入 request并挂载为全局属性$http复制代码import App from ./App.uvueimport { createSSRApp } from vueimport uviewPlus from uview-plus/* 1. 引入 request里面已经初始化好 http */import http from /utils/requestexport function createApp() {const app createSSRApp(App)/* 2. 挂到全局属性 */app.config.globalProperties.$http httpapp.use(uviewPlus)return {app}}复制代码三、使用request由于在main.uts挂载了全局属性因此在pages里面的uvue文件就可以直接调用了。比如get请求const res await this.$http.get(/test, {})post请求const res await this.$http.post(/login, {username: admin,password: 123456})post请求增加成功和失败处理复制代码async login() {try {/* 成功分支 */const res await this.$http.post(/login, {username: admin,password: 123456})// 这里只写“成功后的业务”uni.setStorageSync(token, res.token)this.$u.toast(登录成功)uni.switchTab({ url: /pages/index/index })} catch (err: any) {/* 失败分支 */// 拦截器已弹通用提示这里可做“额外”处理console.error(登录失败, err)if (err.statusCode 401) {this.$u.toast(账号或密码错误)}}}复制代码post请求局部请求不想显示 loadingawait this.$http.post(/log, data, { loading: false })uview-plus 的 http 模块已经内置了 “请求开始自动显示 loading响应结束自动隐藏” 的机制你只需要 把 loading 开关打开 即可成功/失败/超时都会 统一自动关闭无需手动处理。效果调用 this.$http.get/post 瞬间 → 出现 uview-plus 的 loading 遮罩请求 成功/失败/超时 → 遮罩 自动消失由 uview 内部 finally 关闭无需自己 uni.showLoading() / uni.hideLoading()post请求增加header复制代码await this.$http.post(/upload, body, {header: {Content-Type: application/x-wwwz-form-urlencoded,X-Custom: abc123}})复制代码put请求const res await this.$http.put(/test, {id:1})delete请求const res await this.$http.delete(/test, {id:1})四、登录页面login.uvue复制代码复制代码效果如下image针对大型项目可以在utils里面新建一个api.ts用来编写一些公用业务函数例如复制代码import http from ./request.js/* 登录 */export const login (username, pwd) http.post(/login, { username, pwd })/* 轮播图 */export const getBanner () http.get(/banner)/* 商品列表 */export const getGoods (params) http.get(/goods, { params })复制代码然后在pages里面的页面就可以调用了无需重复写函数。复制代码复制代码注意直接调用要用异步函数名前面加async