数据请求
使用wx.reuqest()方法进行数据请求然后传入请求路径url:“路径”
接着是成功或者失败
success:(res)进行log res可以看到请求的数据
路由封装API
首先创建http文件夹
在根目录下穿件env文件夹然后在文件夹里创建index.js文件进行配置多个开发环境并导出
module.exports={
//开发环境
Dev:{
"BaseUrl":"https://www.develep.com"
},
//测试环境
Test:{
"BaseUrl":"https://www.test.com"
},
//生产环境
Prod:{
"BaseUrl": "https://api.douban.com"
}
}
在api中统一管理请求的url路径
module.exports={
"hot":"/v2/movie/in_theaters",
"top250": "/v2/movie/top250",
"detail": "v2/movie/subject"
}
在fetch.js中使用promise对wx.qeurest()进行封装
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
})
})
}
接着在http.js中根据当前的环境设置相应的baseUrl,引入farch.js文件中封装好的promise请求封装基础的get、post请求方法设置请求体带上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)
}
}
在全局app.js文件中导出http.js注册到跟组件
const http=require('./http/http.js')
App({
http, // http.fetch
})
然后在哪页页面应用就导入到哪个页面
const app = getApp();
Page({
data: {
list:[]
}
onLoad: function () {
app.http.hot().then((res)=>{
this.setData({
list: res.data.list
}) })
}