小程序请求接口封装

小程序接口封装

封装接口文件 api.js

// 服务器地址
const host = 'https://xxx.com';
// 请求接口
const apiLogin = host+'Passport/login';
const apiIndexOrder = host+'Index_order/index';
const apiOrderList = host+'Index_order/list';

//通用请求接口方法
const apiRequest = (url,data={},callback,method="post", header) => {//接收所需要的参数,如果不够还可以自己自定义参数
  wx.request({
    url: url,
    data: data ? data : null,
    method: method,
    header: header ? header : { 'content-type':'application/x-www-form-urlencoded'},
    success: function (res) {
      //接口调用成功
         //根据业务需要 返回的json的数据
      console.log('api请求成功')
      console.log(res.data)
      return typeof callback == "function" && callback(res.data)
    },
    fail: function (res) {
      // fail调用接口失败
      return typeof callback == "function" && callback(false)
    }
  })
}

通用图片请求接口方法
// 上传图片
const apiUpload = (url,filePath,callback)=>{
  wx.uploadFile({
    filePath: filePath,
    name: 'file',
    url: url,
    success:function (res) {
      console.log('上传图片成功')
      console.log(JSON.parse(res.data))
      return typeof callback == "function" && callback(JSON.parse(res.data))//返回图片地址
    },
    fail:function (res) {
      return typeof callback == "function" && callback(false)
    }
  })
}

//登录接口
const login = (data,callback)=>{
  apiRequest(apiLogin,data,function(res){
    return typeof callback == "function" && callback(res)
  })
}

// 订单
const indexOrder = (data,callback)=>{
  apiRequest(apiIndexOrder, data,function(res){
    return typeof callback == "function" && callback(res)
  });
}
//流水列表
const orderList = (data,callback)=>{
  apiRequest(apiOrderList, data,function(res){
    return typeof callback == "function" && callback(res)
  });
}

上传图片接口
const uploadImg = (callback)=>{
  wx.chooseImage({
    count:1,
    success(res){  
      let filePath = res.tempFilePaths[0];
      apiUpload(apiUploadImg,filePath,function(res){
        return typeof callback == "function" && callback(res)
      });
    }
  }) 
}

接口模块化
module.exports = {
  login,
  indexOrder, 
  orderList,
  uploadImg
}

调用api方法

const api = require("文件位置");
例:
const api = require("../../utils/api.js");

//引用方法
let data = [];
api.indexOrder(data,function(res){
	console.log(“请求结果”)
      if(res.code == 200){
      // ...
      }
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值