详解微信小程序网络请求接口封装

为实现定制要求和方便调用,对微信小程序的网络请求接口进行了封装
在根目录新建api文件夹并新建httpRequest.js与config.js文件

1.设置请求域名

// 设置请求域名
let ENV = __wxConfig.envVersion
let httpUrl = '',
if (ENV == 'develop') {
  // 测试版开发环境域名
  httpUrl = 'https://*******.com/api';
} else if (ENV == 'trial') {
  // // 体验版环境域名
  httpUrl = 'http://*******.com/api';
} else if (ENV == 'release') {
  // 线上环境域名
  httpUrl = 'https://*******.com/api';
}
export default httpUrl

2.在utils下方一个qs文件

根据自己项目数据需求是否下载qs

3.封装httpRequest

import Qs from '../utils/qs'
import httpUrl from './config'
const apiRequest = (option) => {
  /*
  option.url:请求地址
  option.header:头信息
  option.params:参数
  */
  let promise = new Promise(function (resolve, reject) {
    wx.showLoading({
      title: '努力加载中',
      mask: true
    });
    // 设置请求头
    let headers = {
      'Content-Type': 'application/x-www-form-urlencoded',
      'X-Requested-With': 'XMLHttpRequest'
    }
    // 对数据进行处理转换
    let params = Qs.stringify(option.params, {
      arrayFormat: 'indices',
      allowDots: true
    }).replace(/\[\d+\]=/g, "=")
    wx.request({

      url: httpUrl.connectorUrl + option.url,
      data: params,
      method: 'post',
      header: headers,
      // 超时时间
      timeout: 60000,
      success: function (res) {
        wx.hideLoading()
        if (res.statusCode == 200) {
          res = res.data
          if (res.code == -1) {
            // 跳转到登录

          } else if (res.code == 2) {
            wx.showModal({
              title: '提示',
              content: '您没有访问权限',
              success: function () {
                // 返回上一页
                wx.navigateBack()
                if (res.confirm) {
                  // 点击了确定
                } else if (res.cancel) {
                  // 点击了取消
                }
              }
            })
          } else  {
            // 请求成功
            resolve(res)
          }
        } else if (res.statusCode == 500) {
          wx.showToast({
            title: '后台异常',
            icon: 'none'
          })
        }
      },
      fail: function (res) {
        wx.hideLoading()
        wx.showToast({
          title: res.errMsg,
          image: '/static/icon/error.png'
        })
      }
    })
  })
  return promise
}
module.exports = apiRequest;

4.在api文件中统一处理api请求

import httpRequest from './httpRequest'
export const notaryHistoryPage(params) {
  return httpRequest({ url: '/api/*******', params }).then(res => res)
},

5.页面使用

var api = require('../../api/api.js').default;
Page({
	show:function() {
		let params = {
			id:1
		}
		api.notaryHistoryPage(params).then(res=>{}).catch(res=>{})
	}
})


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值