uniapp与后台交互
uniapp与后台交互的方式
uniapp与后台交互主要通过HTTP请求实现,常用的方法包括内置的uni.request、封装后的uniCloud云开发,以及第三方库如axios的适配。以下是具体实现方法:
使用uni.request发起请求
uni.request是uniapp内置的HTTP请求API,支持Promise风格调用。示例代码:
uni.request({
url: 'https://example.com/api/data',
method: 'GET',
data: { id: 123 },
header: { 'Content-Type': 'application/json' },
success: (res) => console.log(res.data),
fail: (err) => console.error(err)
});
封装全局请求方法
为提高代码复用性,可在main.js中封装全局请求方法:
const http = (options) => {
return new Promise((resolve, reject) => {
uni.request({
...options,
success: (res) => resolve(res.data),
fail: (err) => reject(err)
});
});
};
Vue.prototype.$http = http;
调用方式:
this.$http({ url: '/api/login', method: 'POST', data: { username, password } });
使用uniCloud云开发
uniapp官方提供的uniCloud支持免运维的后端开发:
- 在项目中关联uniCloud服务空间
- 创建云函数:
// 云函数login exports.main = async (event) => { return { code: 200, data: { token: 'mock_token' } }; }; - 前端调用:
uniCloud.callFunction({ name: 'login', data: { user: 'admin' } }).then(res => console.log(res.result));
第三方库适配
在uniapp中使用axios需要特殊配置:
- 安装适配库:
npm install axios @escook/request-miniprogram - 配置适配器:
import axios from 'axios'; import mpAdapter from '@escook/request-miniprogram';
axios.defaults.adapter = mpAdapter; axios.post('/api', { data: 123 }).then(res => {});
### 跨域问题解决方案
开发环境下可能遇到跨域限制,可通过以下方式解决:
- 配置H5端的`devServer.proxy`(vue.config.js):
```javascript
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'https://example.com',
changeOrigin: true
}
}
}
};
- 生产环境使用Nginx反向代理或后台配置CORS头:
Access-Control-Allow-Origin: *
数据缓存策略
结合uni.setStorage实现本地缓存:
// 获取带缓存的数据
const getCachedData = async (key, url) => {
try {
const cache = uni.getStorageSync(key);
if (cache) return cache;
const res = await this.$http({ url });
uni.setStorageSync(key, res.data);
return res.data;
} catch (e) {
console.error(e);
}
};
安全注意事项
- 敏感请求使用HTTPS协议
- 用户凭证通过header传递而非URL参数:
header: { 'Authorization': 'Bearer ' + token } - 关键接口添加请求签名验证
- 输入参数进行合法性校验
调试技巧
- 使用
uni.showLoading和uni.hideLoading管理加载状态 - 通过
console.log和浏览器开发者工具查看网络请求 - 真机调试时开启
debug模式:// manifest.json "h5": { "devServer": { "disableHostCheck": true } }







