目录结构
...
├── images
├── api
│ └── index.js // 首页的接口
│ └── classify.js // 分类的接口
│ └── ...
├── pages
│ └── index
├── utils // 工具类
│ └── request.js // 请求封装
└── package.json
...
基本说明
- 此方法是基于微信小程序API wx.request 的简单封装,方法中暂有4个参数,若后期需要可自行添加。函数返回一个promise用来执行一个异步操作。
- Promise可以理解为一个承诺,它有3种状态:**pending(进行中)**,**fulfilled(已成功)**,**rejected(已失败)**,当Promise执行成功时,成功状态会在其参数resolve中接收并传到then的参数中去,失败则是reject。
小程序请求封装
...js (utils/request.js)
// 请求api的基础路径
export const baseUrl = 'http://xxxxxxxxx/com'
/**
* 统一的请求封装
* @param {String} api 请求的api地址
* @param {JSON} params 请求携带的参数
* @param {String} methods 请求方式,默认GET
* @param {boolean} [loading=true] 是否显示loading,默认true
*/
export function appRequest(api, params, method = 'POST', loading = true) {
return new Promise((resolve, reject) => {
// 请求开始,显示loading
if (loading) {
wx.showLoading({
title: '加载中'
})
}
// 请求
wx.request({
url: baseUrl + api,
data: params,
method: method,
dataType: 'json',
success: function(res) {
if (res.statusCode === 200) {
resolve(res) // 接收res并传到then的参数中去
wx.hideLoading() // 结束加载
} else {
wx.hideLoading()
reject()
}
},
error: function(e) {
reject(e)
}
})
})
}
在页面js文件中的用法
...js (pages/index/index.js)
// 引入请求函数
import { appRequest } from "../../utils/request.js"
// 引入请求api
import { swiperJson,scheduleJson } from "../../api/index.js"
Page({
/**
* 页面的初始数据
*/
data: {
swiperJson: null, // 返回的轮播图数据
scheduleJson: null // 赛程json
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
// 加载轮播图
this.getSwiperJson()
// 加载赛程
this.getScheduleJson()
},
// 请求数据库获得轮播图
getSwiperJson() {
appRequest(swiperJson).then(res => {
console.log(res)
this.setData({
swiperJson: res.data
})
})
},
// 请求数据库获得赛程
getScheduleJson() {
appRequest(scheduleJson).then(res => {
console.log(res)
this.setData({
scheduleJson: res.data
})
})
}
})
导出请求api
...js (pages/api/index.js)
// 轮播图
export const swiperJson = "/WxIndex/swiper.action"
// 赛程
export const scheduleJson = "/WxIndex/schedule.action"
//...