封装请求创建request.js文件,把一下内容根据自己的需求更改。
//封装请求方法//声明一个请求函数const api_request=(url, method, parm)=>{ console.log(1111111111); var apiurl = getApp().globalData.BASE_URL+'/api.php'; //域名 + api.php var timestamp = Date.parse(new Date()); timestamp = timestamp / 1000; //获取当前时间戳 //因为搜索、留言和表单需要用到POST方法,要通过data传递参数,所以先声明data对象,方便后面添加 var data = { timestamp: timestamp }; //根据请求方法构建Header if (method == 'POST') { //POST方法,设置请求头部 var header = { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' }; //添加POST参数到data for (var i in parm) { data[i] = parm[i]; } } else { //GET方法,设置请求头部 method = 'GET'; var header = { 'Content-Type': 'application/json' }; } //通过promise返回数据 var promise = new Promise(function(resolve,reject){ //小程序自带的wx.request请求 uni.request({ method: method, url: apiurl + url, header: header, data: data, //请求成功 success: function(res){ var api_data = res.data; if (api_data.code != 1 && api_data.code != 0){ reject({ error: '数据请求失败,请稍后重试', code: 500 }); return; } else { resolve(api_data); } } }) }) //返回数据 return promise;};export default api_request
api封装:创建api.js来放你需要封装的api.
import api_request from "@/pages/api/request.js" //先导入封装好的request文件//Api模块//获取公司信息const companyinfos = async () => {var url = '/cms/company';let data = await api_request(url);return data;}//获取网站信息const siteinfos = async () => {var url = '/cms/site';let data = await api_request(url);return data;}uni.service = {companyinfos,siteinfos}
调用时
来源地址:https://blog.csdn.net/qq_43003057/article/details/126331186