uniapp与后台交互
uniapp与后台交互的方式
uniapp提供了多种与后台服务器交互的方法,主要包括以下几种:
使用uni.request进行HTTP请求
uni.request是uniapp中最常用的与后台交互的方式,基于微信小程序的request API封装,支持GET、POST等HTTP方法。基本用法如下:
uni.request({
url: 'https://example.com/api',
method: 'GET',
data: {
key1: 'value1',
key2: 'value2'
},
success: (res) => {
console.log(res.data);
},
fail: (err) => {
console.error(err);
}
});
使用WebSocket进行实时通信
对于需要实时双向通信的场景,可以使用uni.connectSocket创建WebSocket连接:
const socket = uni.connectSocket({
url: 'wss://example.com/ws',
success: () => {
console.log('连接成功');
}
});
socket.onMessage((res) => {
console.log('收到消息', res.data);
});
使用uni.uploadFile上传文件
文件上传需要使用专门的uni.uploadFile方法:
uni.chooseImage({
success: (chooseRes) => {
const tempFilePaths = chooseRes.tempFilePaths;
uni.uploadFile({
url: 'https://example.com/upload',
filePath: tempFilePaths[0],
name: 'file',
formData: {
'user': 'test'
},
success: (uploadRes) => {
console.log(uploadRes.data);
}
});
}
});
使用uni.downloadFile下载文件
文件下载功能可以通过uni.downloadFile实现:
uni.downloadFile({
url: 'https://example.com/file.pdf',
success: (res) => {
if (res.statusCode === 200) {
const filePath = res.tempFilePath;
uni.saveFile({
tempFilePath: filePath,
success: (savedRes) => {
console.log('文件保存成功', savedRes.savedFilePath);
}
});
}
}
});
请求封装与全局配置
在实际项目中,通常会封装请求函数以便统一管理:
// api.js
const baseURL = 'https://example.com/api';
function request(options) {
return new Promise((resolve, reject) => {
uni.request({
url: baseURL + options.url,
method: options.method || 'GET',
data: options.data || {},
header: {
'Content-Type': 'application/json',
'Authorization': uni.getStorageSync('token')
},
success: (res) => {
if (res.statusCode === 200) {
resolve(res.data);
} else {
reject(res.data);
}
},
fail: (err) => {
reject(err);
}
});
});
}
export const getData = (params) => request({ url: '/data', method: 'GET', data: params });
export const postData = (data) => request({ url: '/data', method: 'POST', data });
跨域问题处理
在开发环境中可能会遇到跨域问题,可以通过以下方式解决:
-
配置H5端的devServer代理(vue.config.js):
module.exports = { devServer: { proxy: { '/api': { target: 'https://example.com', changeOrigin: true, pathRewrite: { '^/api': '' } } } } }; -
生产环境通过后端配置CORS或使用Nginx反向代理解决跨域问题。
数据缓存策略
为了提高用户体验,可以考虑使用本地缓存:
// 优先从缓存获取数据,不存在则请求接口
function getCachedData(key) {
return new Promise((resolve) => {
uni.getStorage({
key,
success: (res) => {
resolve(res.data);
},
fail: () => {
request({ url: '/data/' + key }).then(data => {
uni.setStorage({ key, data });
resolve(data);
});
}
});
});
}
错误处理与拦截
可以封装统一的错误处理逻辑:
// 请求拦截
uni.addInterceptor('request', {
invoke(args) {
// 请求前添加loading
uni.showLoading({ title: '加载中' });
},
success(args) {
// 请求成功隐藏loading
uni.hideLoading();
},
fail(err) {
// 请求失败处理
uni.hideLoading();
uni.showToast({ title: '请求失败', icon: 'none' });
}
});
注意事项
- 小程序平台对请求域名有白名单限制,需要在manifest.json中配置request合法域名
- 注意不同平台的兼容性问题,特别是H5和小程序的差异
- 对于敏感数据,建议使用HTTPS协议传输
- 合理设置请求超时时间,避免长时间等待
- 考虑网络状态检测,可以在发起请求前检查网络连接状态







