微信小程序实现 API Promise 化

微信小程序实现 API Promise 化

例子wx.request

1.new Promise()化
新建reque.js

// ----request.js----
const apiUrl = "https://接口地址:端口";// 公共的请求地址
// 封装微信请求方法
const request = (params) => {
  let url = params.url;
  let data = params.data || '';
  let method = params.method || 'GET';
  let header = {
    "Content-Type": "application/json"
  }; //头部按需
  // 鉴权验证,获取登录之后后端返回的token,存在即在头部Authorization写token,具体的看后端需求
  if (wx.getStorageSync("token")) {
    // header.Authorization = wx.getStorageSync("token");
    header.token = wx.getStorageSync("token");
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: apiUrl + url, // api url
      method: method, // get/post
      data: data, // 请求参数
      header: header, // 头部
      success(res) {
        // 请求成功
          resolve(res.data);
      },
      fail(err) {
          wx.showToast({
            title: '网络异常',
            icon: "error",
            duration: 2000
          })
      
        reject(err);
      },
      complete() {
        wx.hideLoading()
      },
    });
  });
};

module.exports = {
  request
}

使用

import {request} from "./request"


// 用户相关

// 登录
export const login = (params) => {
  return request({
    url: '/user/login',
    data: params,
    method: 'POST',
  })
}
// 注册
export const register = (params) => {
  return request({
    url: '/user/reg',
    data: params,
    method: 'POST',
  })
}

2.用第三方包来实现

npm install --save miniprogram-api-promise@1.0.4 

删除 miniprogram_npm 文件夹
在这里插入图片描述
重新构建npm
在相关js文件里使用

import {promisifyAll} from 'miniprogram-api-promise'
const wxp = wx.p = {}
promisifyAll(wx,wxp)
Page({
	 async getInfo(){
	 // const res = await wxp.request
	        const res = await wx.p.request({
	            url:'http://pcapi-xiaotuxian-front-devtest.itheima.net/home/new'
	        })
	        console.log(res);
	    },
      /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getInfo()
    },

})

uniapp里实现

npm install @escook/request-miniprogram
// ---main.js---
// 将按需导入的 $http 挂载到 wx 顶级对象之上,方便全局调用
// wx.$http = $http

// 在 uni-app 项目中,可以把 $http 挂载到 uni 顶级对象之上,方便全局调用
uni.$http = $http
// 配置请求根路径
$http.baseUrl = 'https://www.uinav.com'
// 请求开始之前做一些事情
$http.beforeRequest = function (options) {
uni.showLoading({
title: '数据加载中...',
})
}
// 请求完成之后做一些事情
$http.afterRequest = function () {
uni.hideLoading()
}

使用

export default {
data() {
return {
// 1. 轮播图的数据列表,默认为空数组
swiperList: [],
}
},
onLoad() {
// 2. 在小程序页面刚加载的时候,调用获取轮播图数据的方法
this.getSwiperList()
},
methods: {
// 3. 获取轮播图数据的方法
async getSwiperList() {
// 3.1 发起请求
const { data: res } = await uni.$http.get('/api/public/v1/home/swiperdata')
// 3.2 请求失败
if (res.meta.status !== 200) {
return uni.showToast({
title: '数据请求失败!',
duration: 1500,
icon: 'none',
})
}
// 3.3 请求成功,为 data 中的数据赋值
this.swiperList = res.message
},
},
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值