在hbuilderx中开发uni-app时,应封装uni.request为request工具函数,统一处理baseurl、token注入、超时配置及状态码判断,并导出get/post快捷方法,避免重复逻辑和错误遗漏。

在HBuilderX中开发uni-app项目时,直接用uni.request调接口容易重复写header、处理token、判断状态码,每次都要复制粘贴相同逻辑,稍不注意就漏掉错误处理或超时配置。
基础GET请求:不用封装也能快速发起
第一步:打开任意.vue文件,在methods里写一个函数,比如getBannerList;
第二步:调用uni.request({}),url填完整地址(含协议),method设为'GET';
第三步:在success回调里用console.log(res)先看返回结构,确认data字段位置再赋值给this变量;
注意:如果后端返回的是字符串而非JSON,需手动JSON.parse(res.data),否则this.bannerList = res.data会报类型错误。
基础POST请求:传参格式必须匹配后端要求
方法一:发送表单数据(application/x-www-form-urlencoded)
data直接传对象,uni.request会自动序列化成key=value&key2=value2格式;
方法二:发送JSON数据(application/json)
data传JSON对象,同时在header里显式设置【'content-type': 'application/json'】;
这一步不能省——不加这个header,很多后端框架(如Spring Boot)会直接拒收,返回400错误且不提示原因。
封装request工具:统一管理超时、token和错误响应
① 在项目根目录下新建utils/request.js文件;
② 写入以下代码(兼容GET/POST,自动拼接baseUrl,带token注入):
import { baseUrl } from '@/utils/baseUrl.js'
export function request(config) {
const token = uni.getStorageSync('token') || ''
return new Promise((resolve, reject) => {
uni.request({
url: baseUrl + config.url,
method: config.method || 'GET',
data: config.data || {},
header: {
'Authorization': token ? `Bearer ${token}` : '',
'content-type': config.header?.['content-type'] || 'application/json'
},
timeout: config.timeout || 10000,
success: res => {
if (res.statusCode >= 200 && res.statusCode resolve(res.data)
} else if (res.statusCode === 401) {
uni.navigateTo({ url: '/pages/login/login' })
reject(new Error('登录已过期'))
} else {
reject(res)
}
},
fail: err => reject(err)
})
})
}
③ 在需要调用的页面顶部import { request } from '@/utils/request.js';
④ 使用时直接写:request({ url: '/api/user/info', method: 'GET' }).then(data => this.userInfo = data);
封装GET/POST快捷方法:让页面调用更简洁
在utils/request.js末尾追加两行导出语句:
export const get = (url, data) => request({ url, method: 'GET', data })
export const post = (url, data) => request({ url, method: 'POST', data })
然后在页面里就可以这样写:
import { get, post } from '@/utils/request.js'
get('/api/list', { page: 1 }).then(res => this.list = res.items)
post('/api/login', { phone: '138****1234', code: '666666' }).then(res => uni.setStorageSync('token', res.token))
这比每次都写request({ method: 'GET' ... })少敲12个字符,长期下来节省大量键盘磨损。










