小程序网络请求封装

爱被打了一巴掌 2022-02-26 12:52 405阅读 0赞

目录结构


├── 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)

  1. // 请求api的基础路径
  2. export const baseUrl = 'http://xxxxxxxxx/com'
  3. /**
  4. * 统一的请求封装
  5. * @param {String} api 请求的api地址
  6. * @param {JSON} params 请求携带的参数
  7. * @param {String} methods 请求方式,默认GET
  8. * @param {boolean} [loading=true] 是否显示loading,默认true
  9. */
  10. export function appRequest(api, params, method = 'POST', loading = true) {
  11. return new Promise((resolve, reject) => {
  12. // 请求开始,显示loading
  13. if (loading) {
  14. wx.showLoading({
  15. title: '加载中'
  16. })
  17. }
  18. // 请求
  19. wx.request({
  20. url: baseUrl + api,
  21. data: params,
  22. method: method,
  23. dataType: 'json',
  24. success: function(res) {
  25. if (res.statusCode === 200) {
  26. resolve(res) // 接收res并传到then的参数中去
  27. wx.hideLoading() // 结束加载
  28. } else {
  29. wx.hideLoading()
  30. reject()
  31. }
  32. },
  33. error: function(e) {
  34. reject(e)
  35. }
  36. })
  37. })
  38. }

在页面js文件中的用法

…js (pages/index/index.js)

  1. // 引入请求函数
  2. import { appRequest } from "../../utils/request.js"
  3. // 引入请求api
  4. import { swiperJson,scheduleJson } from "../../api/index.js"
  5. Page({
  6. /**
  7. * 页面的初始数据
  8. */
  9. data: {
  10. swiperJson: null, // 返回的轮播图数据
  11. scheduleJson: null // 赛程json
  12. },
  13. /**
  14. * 生命周期函数--监听页面加载
  15. */
  16. onLoad: function(options) {
  17. // 加载轮播图
  18. this.getSwiperJson()
  19. // 加载赛程
  20. this.getScheduleJson()
  21. },
  22. // 请求数据库获得轮播图
  23. getSwiperJson() {
  24. appRequest(swiperJson).then(res => {
  25. console.log(res)
  26. this.setData({
  27. swiperJson: res.data
  28. })
  29. })
  30. },
  31. // 请求数据库获得赛程
  32. getScheduleJson() {
  33. appRequest(scheduleJson).then(res => {
  34. console.log(res)
  35. this.setData({
  36. scheduleJson: res.data
  37. })
  38. })
  39. }
  40. })

导出请求api

…js (pages/api/index.js)

  1. // 轮播图
  2. export const swiperJson = "/WxIndex/swiper.action"
  3. // 赛程
  4. export const scheduleJson = "/WxIndex/schedule.action"
  5. //...

发表评论

表情:
评论列表 (有 0 条评论,405人围观)

还没有评论,来说两句吧...

相关阅读