小程序请求封装

本文介绍了在项目开发中如何根据不同环境(开发、测试、生产)切换接口域名,并展示了如何封装请求函数以简化代码,包括POST和GET请求的实现方式及调用示例,便于代码维护和复用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在项目的开发中有三个环境

开发环境
测试环境
生产环境
访问接口数据时,例如:商品接口会是【域名】/api/xxx/xxx
当环境不同时,直接修改域名即可。这是为什么要封装请求。

一、封装的意义

代码更简单,维护更方便

var api= 'http://10.1.8.22:1001';//域名
  apiList: {
    usersLogin: api+ '/storeroom/usersLogin/usersLogin', //登录  
    queryCustomersList: api+ '/storeroom/repertory/queryCustomersList', //查询客户  
    insertCustomersBatch: api+ '/storeroom/repertory/insertCustomersBatch', //查询客户  
  },

二、使用步骤

1.post请求

代码如下(示例):

  apiPost: function (api, data, callback) {
    var that = this;
    //请求头
    var header = {
      // 'content-type': 'application/x-www-form-urlencoded'
    };
    //请求
    wx.request({
      url: api,
      data: data,
      method: 'POST',
      dataType: 'json',
      header: header,
      success: (res) => {
        // console.log("res:", res);
        return callback(res.data);//成功后回调    
      },
      fail: function (res) {
        wx.showModal({
          //  cancelColor: 'cancelColor',
          title: '调用出错啦',
          content: res
        })
      },
      complete: function (res) {
        console.log("res:", res);
      }
    })
  },

调用

 app.apiPost(app.apiList.usersLogin+that.data.username+'/'+that.data.password,{},res=>{
		console.log(res)
})

2.get请求

代码如下(示例):

  apiGet: function (api, data, callback) {
    var header = {
      'content-type': 'application/json;charset=UTF-8',
      "X-Requested-With": 'XMLHttpRequest',
    };
    wx.request({
      url: api,
      data: data,
      method: 'GET',
      dataType: 'json',
      header: header,
      success: function (res) {
        callback(res.data)
      },
      fail: function (res) {
        console.error(api+ '请求失败')
      },
      complete: function (res) {

      }
    })
  },

调用

  app.apiGet(app.apiList.queryCustomersList,data,res=>{//data就是拼接在api路径后所需的参数
	console.log(res)
})
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值