如何封装微信小程序的数据请求

it2023-09-02  71

如何封装微信小程序的数据请求

1、首先创建一个http文件夹 目录如下 2、在根目录下创建env目录,创建index.js配置并导出多个开发环境

module.exports={ //开发环境 Dev:{ "BaseUrl":"https://www.develep.com" }, //测试环境 Test:{ "BaseUrl":"https://www.test.com" }, //生产环境 Prod:{ "BaseUrl": "https://api.douban.com" } }

3、在api.js中统一管理,请求的url地址

module.exports={ "hot":"/v2/movie/in_theaters", "top250": "/v2/movie/top250", "detail": "v2/movie/subject" }

4、在fetch.js中用promise对wx.request()进行封装

//封装 http module.exports= (url, path,method, params)=>{ return new Promise((resolve, reject) => { wx.request({ url: `${url}/${path}`, method:method, data: Object.assign({}, params), header: { 'Content-Type': 'application/text' }, success: resolve, fail: reject }) }) }

5、在http.js , 根据当前的环境,设置相应的的baseUrl,引入fetch中封装好的promise请求, 封装基础的get \ post \ put \ upload等请求方法,设置请求体,带上token和异常处理; 设置方法并导出

const api = require('./api.js') const config=require('../env/index.js'); const fetch=require('./fetch.js'); let Env='Prod'; let baseUrl = config[Env].BaseUrl; let key ='?apikey=0b2bdeda43b5688921839c8ecb20399b' console.log(baseUrl); console.log(api) function fetchGet(path,params){ return fetch(baseUrl,path,'get',params); } function fetchPost(path,params){ return fetch(baseUrl,path,'post',params); } module.exports={ hot(paramas={}){ return fetchGet(api.hot+key,paramas); }, top250(params={}){ return fetchGet(api.top250+key,params); }, detail(id,params={}){ return fetchGet(api.detail+`/${id}`+key,params) } }

6、在全局app.js中导出http.js注册到根组件

const http=require('./http/http.js') App({ http, // http.fetch })

7、在具体页面导入并且使用

//获取应用实例 const app = getApp(); Page({ data: { list:[] } onLoad: function () { app.http.hot().then((res)=>{ this.setData({ list: res.data.list }) }) }
最新回复(0)