module.exports={ //开发环境 Dev:{ "BaseUrl":"https://www.develep.com" }, //测试环境 Test:{ "BaseUrl":"https://www.test.com" }, //生产环境 Prod:{ "BaseUrl": "https://api.douban.com" } }
module.exports={ "hot":"/v2/movie/in_theaters", "top250": "/v2/movie/top250", "detail": "v2/movie/subject" }
//封装 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 }) }) }
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) } }
const http=require('./http/http.js') // App.config=config[env]; App({ http, // http.fetch })
//获取应用实例 const app = getApp(); Page({ data: { list:[] } onLoad: function () { app.http.hot().then((res)=>{ this.setData({ list: res.data.list }) }) }