使用网络请求后台数据

现在网络无处不在,掌握网络请求,是一项必须的技能。

小程序HTTP网络开发非常简单。小程序官方提供了HTTP的三个请求API,分别是网络请求request,上传文件uploadfile,下载文件downloadfile。我们使用这三个API,去实现我们的需求。

在使用本地开发者工具开发小程序时,默认不要勾选检验域名,方便我们调试。当上线的时候,我们需要将后台的域名配置到小程序后台域名白名单中。

我们需要请求文章列表。我设计了两个接口,一个接口根据关键字查询文章列表,一个接口根据快接按钮属性查询文章列表。

根据按钮属性查询文章列表代码如下:


  // 根据类型查询
  getArtList: function (pageNo, qtype) {
    const that = this

    that.loading = true
    wx.showLoading({
      title: '加载中...',
      mask: true,
    })
    if (pageNo === 1) {
      that.setData({
        artList: [],
      })
    }

    httpGet('/artl', {
      'pageNo': pageNo,
      'qtype': qtype,
    }).then((res) => {
      that.loading = false
      wx.hideLoading()

      const result = res.data;
      if (result.code == 1) {
        const articles = result.data;
        that.setData({
          page: pageNo, //当前的页号
          pages: result.count, //总页数
          artList: that.data.artList.concat(articles)
        })

      } else {
        wx.showToast({
          title: '没有找到记录',
        })
      }
    }).catch((err) => {
      that.loading = false
      wx.hideLoading()
      wx.showToast({
        title: '网络异常请重试',
      })
    })

  },

根据关键字查询文章列表代码如下:


  searchArt: function (pageNo, keyword) {
    const that = this

    that.loading = true
    wx.showLoading({
      title: '加载中...',
      mask: true,
    })
    if (pageNo === 1) {
      that.setData({
        artList: [],
      })
    }

    httpGet('/sart', {
      'pageNo': pageNo,
      'keyword': keyword,
    }).then((res) => {
      that.loading = false
      wx.hideLoading()
      const result = res.data;
      if (result.code == 1) {
        const articles = result.data;
        that.setData({
          page: pageNo, //当前的页号
          pages: result.count, //总页数
          artList: that.data.artList.concat(articles)
        })

      } else {
        wx.showToast({
          title: '没有找到记录',
        })
      }
    }).catch((err) => {
      that.loading = false
      wx.hideLoading()
      wx.showToast({
        title: '网络异常请重试',
      })
    })

  },

两个方法大体框架差不多,后台接口名不一样。在这里,我多说两句,这两个接口可以合并成一个接口,有好处也有坏处。好处是减少接口的数量,坏处是减少了灵活性,耦合性太强,修改一个接口内容会影响到另一个接口。所以大家可以根据实际需求来设计。我经历的好多接口都是合并之后,新增需求后再拆开,优化时再合并。

网络请求这块讲的不多,大多时间都是和后台的调试。我们的需求,没有用到文件上传和文件下载。这两个API也非常的简单。我的另一个小程序【豆子工具】中有用到,可以看看它的项目实践教程。

当获取到数据后,赋值给artList,小程序会自动渲染数据到页面。另外两个数据page和pages是为了分页使用。

 that.setData({
          page: pageNo, //当前的页号
          pages: result.count, //总页数
          artList: that.data.artList.concat(articles)
        })

当数据渲染到首页后,我们就可以看到文章列表,当点击文章列表中的某个文章项时,会跳转到文章详情。

下一节,我们讲解小程序解析Markdown格式内容。