1,根目录中新建config.js文件
/*
* 小程序接口封装:
1,创建config.js
配置公共的请求接口地址以及其他全局参数
2,在utils目录下新建http.js/ request.js
封装wx.request配置
3,在根目录下创建api文件夹,根据对应的接口模块创建对应接口文件,在文件内封住对应的接口
4,在页面内调用封装的接口
需要进行实例化
*/
const config = {
//公共的接口地址
api_base_url: 'http://weixin.itying.com',
//接口所需的appKey 类似token 请求接口时需要校验的数据
// appkey: '-----------------'
}
//ES6MOdule export按需导出 列:export function Fu(){}
//接收时import 需要用结构赋值的方式接收 import {Fu} from ""
export {
config
}
2,在utils文件中新建request文件
//引入公共的接口地址
import { config } from "../config"
//声明变量 用于容错处理
const tips = {
"1": "抱歉出现一个错误",
"1000": "输入参数错误",
'1001': "找不到资源",
'1002': "未知错误"
}
//使用class类配置接口配置,类似于配置axios
class HTTP {
request({ url, method = "GET", data = {} }) {
//返回一个Promise对象, 调用时可以使用Promise的方法 .then .catch
return new Promise((resolve, reject) => {
this._request(url, method, data, resolve, reject)
})
}
_request(url, method = "GET", data = {}, resolve, reject) {
wx.request({
url: config.api_base_url + url,
method: method,
data: data,
//传入头部信息
// header: {
// appkey: config.appkey
// },
success: (response) => { //接口请求成功时返回的值
//进行容错处理 让后台返回的结果直观明了
let code = response.statusCode.toString()
//后台返回过来的状态码是数字,我们需要给他转为字符串,使用startsWith进行判断状态码是否是2开头的
if (code.startsWith("2")) {
console.log(response);
resolve(response)
} else {
reject() //返回错误
let error_code = response.data.status
this._show_error(error_code)
}
},
fail: (error) => { //接口请求失败时返回的数据
this._show_error('1')
reject(error)
}
})
}
//容错方法
_show_error(error_code) {
//没有状态码的情况下
if (!error_code) {
//让错误的状态码为1
error_code = 1;
}
//获取状态码对应的信息
let tip = tips[error_code];
//提示信息
wx.showToast({
title: tip ? tip : tips["1"],
icon: "none",
duration: 2000
})
}
}
export {
HTTP,
}
3,新建API文件夹,用于封装对应模块的请求接口
import { HTTP } from "../utils/request"
class IndexModel extends HTTP {
getProductApi(qcode) {
return this.request({
url: '/api/getProduct',
method: "GET",
data: {
qcode
}
})
}
}
export {
IndexModel
}
4,页面引入时
import { IndexModel } from "../../api/saoma"
const indexModel = new IndexModel();
/*封装接口时使用class类封装的,需要实例化后才能调用*/