微信小程序实现 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
},
},
}