小程序接口封装、异步加载、Promise

目录

1、页面准备

2、在app.js中处理当前环境以便切换api的环境、公共变量

3、定义post、get请求方法 request.js

4、api.js 接口列表调用index.js的post、get请求

5、index.js 需要返回数据的页面

api.js 、index.js 示例

异步实现 async、await


1、页面准备

目录结构:pages > index       与pages同级 utils > request.js、api.js

①页面index.js

②封装的post、get请求方法request.js

③接口请求列表 api.js(相同业务模块下的api可以统一整理到一个js中,方便管理修改等,也可不放同一个js中)

2、在app.js中处理当前环境以便切换api的环境、公共变量

// app.js
  //定义环境变量,和 api域名
  let env, apiUrl = 'https://appapi.5i5j.com';
  if (typeof __wxConfig === 'object') {
    let version = __wxConfig.envVersion;
    if (version === 'develop') {//开发版
      env = 'dev';
    } else if (version === 'trial') {//体验版 
      env = 'trial';
    } else { //生产
      env = 'release';
    }
  }
  //通过环境变量判断当前域名环境
  // apiUrl = env == 'release' ? '生产环境api' : '联调环境api';
  apiUrl = env == 'release' ? 'https://xxx.com' : 'https://xxx-test.com';
  console.log('当前环境:',env)

App({
  onLaunch() {
  },
  globalData: { //全局变量
    hostUrl:apiUrl, //api域名
    cityid:1 //接口上需要的城市
  }
})

3、定义post、get请求方法 request.js

//request.js
/***
 * POST请求
 * @param url 接口地址
 * @param data 请求参数
 * @param config 设置请求头
 */
export const post = (url, data = {}, config = {}) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url,
      data,
      ...config,
      method: "POST",
      success: res => resolve(res),
      fail: err => reject(err)
    })
  })
}
/***
 * GET请求
 * @param url 接口地址
 * @param data 请求参数
 * @param config 设置请求头
 */
export const get = (url, data = {}, config = {}) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: url + parmasFormat(data),
      ...config,
      method: "GET",
      success: res => resolve(res),
      fail: err => reject(err)
    })
  })
}
/***
 * 处理GET请求地址拼接 
 * @param obj 请求的参数对象
 * @param 如 {a:1,b:2} 返回?a=1&b=2
 */
export const parmasFormat = (obj) => {
  let paramsStr = ""
  Object.keys(obj).forEach((key, index) => {
    paramsStr += (index === 0 ? '?' : '&') + key + '=' + (obj[key] ?? '')
  })
  return paramsStr
}

4、api.js 接口列表调用index.js的post、get请求

// api.js

//引入request.js 中的 POST、GET请求
import { post , get } from "./request"

const app = getApp()//获取App()的实例
const { globalData } = app //获取全局变量
const { hostUrl ,cityid } = globalData //获取api域名和城市 ,如果有多个可以这样分开写 ,如果只有一个可以和上一行写一起

/***
 * POST请求
 * @param hostUrl app.js中的接口域名
 * @param data 需要的参数
 * 1、请求头不需要传特殊参数
 */
export const postTest1 = data => post(
  hostUrl + `接口地址` ,
  data,
  {
    header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'},
  }
)

/***
 * POST请求
 * @param hostUrl app.js中的接口域名
 * @param data 需要的参数
 * @param config 设置的header参数
 * 2、请求头需要传特殊参数
 */
export const postTest2 = (data,config) => post(
  hostUrl + `接口地址` ,
  data,
  config
)

/***
 * GET请求
 * @param hostUrl app.js中的接口域名
 * @param params 接口需要的参数
 * 1、请求头需要传特殊参数
 */
export const getTest= (params) => get(hostUrl + "接口地址", 参数对象)
/***
 * GET请求
 * @param hostUrl app.js中的接口域名
 * @param params 接口需要的参数
 * @param config 设置的header参数
 * 2、请求头需要传特殊参数
 */
export const getTest2 = (params,config) => get(hostUrl + "接口地址", 参数对象,设置的header)

5、index.js 需要返回数据的页面

// index.js
// 获取应用实例
const app = getApp()

//导入api请求列表  { 这里面的值对应的是 api 中的 postTest1:不单独设置header postTest2:单独设置header}
//import { 这里对应api里定义好的请求,用哪个写哪个,不需要的可以不写} from "../../utils/api"
import { postTest1 , postTest2, getTest,getTest2} from "../../utils/api"

Page({

  data: { },
  onLoad() { 
    //请求参数
    let params = {
		参数名1:值,
		参数名2:值
    }
    //设置请求头
    let headers= {
	    header:{
		    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8', 
		    'deviceid': '设备id',
	    }
    }

    //header 里不需要单独在设置特别参数
	postTest1(params).then(res => {
      if(res.statusCode == '200'){
        console.log('success',res)
      }else{
        console.log('error',res)
      }
    })
    //设置请求头的请求
	postTest1(params,headers).then(res => {
      if(res.statusCode == '200'){
        console.log('success',res)
      }else{
        console.log('error',res)
      }
    })
    //get 不设置header
    getTest(params).then(res =>{
      console.log('success',res)
    }).catch((err) => {
      console.log('err',err)
    })

    //get 设置header
    getTest2(params,headers).then(res =>{
      console.log('success',res)
    }).catch((err) => {
      console.log('err',err)
    })

  }

})

api.js 、index.js 示例

// api.js

//引入request.js 中的 POST、GET请求
import { post , get } from "./request"

const app = getApp()//获取App()的实例
const { globalData } = app //获取全局变量
const { hostUrl ,cityid } = globalData //获取api域名和城市 ,如果有多个可以这样分开写 ,如果只有一个可以和上一行写一起

/***
 * POST请求  例如1
 * @param hostUrl app.js中的接口域名
 * @param data  接口需要的参数
 * 1、请求头不需要传特殊参数
 */
export const post1 = data => post(
  hostUrl + `/brokering/${cityid}/v1/brokerlist` ,
  data,
  {
    header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'},
  }
)

/***
 * POST请求 例如2
 * @param hostUrl app.js中的接口域名
 * @param data 接口需要的参数
 * @param config 设置的header参数
 * 2、请求头需要传特殊参数
 */
export const post2 = (data,config) => post(
  hostUrl + `/appapi/renting/${cityid}/v1/list` ,
  data,
  config
)


/***
 * GET请求  例如3
 * @param hostUrl app.js中的接口域名
 * @param params 接口需要的参数
 * 1、请求头不需要传特殊参数
 */
export const get1 = (params) => get(hostUrl + "/appapi/sale/v2/recommend/index", params)

/***
 * GET请求  例如4
 * @param hostUrl app.js中的接口域名
 * @param params 接口需要的参数
 * @param config 设置的header参数
 * 2、请求头需要传特殊参数
 */
export const get1 = (params,config) => get(hostUrl + "/appapi/sale/v2/recommend/index", params,config)
// index.js
// 获取应用实例
const app = getApp()

import { post1 , post2 ,get1 ,get2 } from "../../utils/api"

Page({
  data: { },
  onLoad() { 
    let params = {
      cityid:1,
      communityid:200013141
    }
    let headers= {
      header:{
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8', 
        'deviceid': '123',
      }
    }
    post1(params).then(res => {
      if(res.statusCode == '200'){
        if(res.data.status == '200'){
          console.log('res',res.data.data)
        }
      }else{
        console.log(res.data.msg)
      }
    })
    
    post2(params,headers).then(res => {
      if(res.statusCode == '200'){
        if(res.data.status == '200'){
          console.log('listHouse,res',res)
        }
      }else{
        console.log(res.data.msg)
      }
    })

    get1(params).then(res =>{
      console.log('res2',res)
    }).catch((err) => {
      console.log(err)
    })

    get2(params,headers).then(res =>{
      console.log('res3',res)
    }).catch((err) => {
      console.log(err)
    })
  },
})

异步实现 async、await

onLoad: async function (options) {
    let params = {
      cityid:1,
      communityid:200013141
    }
    await list(params).then(res => {
      if(res.statusCode == '200'){
        if(res.data.status == '200'){
          console.log('res',res)
        }
      }else{
        console.log(res.data.msg)
      }
    })

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值