uniapp中使用uni.request()方法获取数据
1.创建文件 utils/request.js
// 导入配置文件的根路径
import config from './baseConfig.js';
// 封装请求方法
//参数:(1.请求路径,2.数据,3.传递法式默认get)
export default ((url, method = 'GET', data = {}) => {
return new Promise((resolve, reject) => {
uni.request({
// 小程序请求此接口
// #ifdef MP-WEIXIN
url: config.baseUrl + url,
// #endif
// h5请求此接口
// #ifdef H5
url,
// #endif
method,
data,
success: (res) => {
// console.log(res);
resolve(res.data)
},
fail: (erro) => {
reject(erro)
}
})
})
})
2.创建文件 utils/config.js
//单独配置更路径,方便后期修改
export default{
baseUrl:'http://localhost:7788'
}
3.使用:在index/index.vue中
// 1.导入封装好的请求数据方法
import http from '../../untils/request.js'
methods: {
// 2.请求首页数据
async getIndexData() {
// #ifdef H5
let res = await http('/api/getIndexData')
// console.log('h5数据请求成功');
// console.log(res);
this.indexData = res.indexData;
// #endif
// #ifdef MP-WEIXIN
let res = await http('/getIndexData')
// console.log('微信小程序数据请求成功');
// console.log(res);
this.indexData = res.indexData;
// #endif
}
}