小程序请求后台API接口一般都用wx.request来调用,但是为了规范管理和后续升级,封装了通用的请求方法
新建http.js : getHeader方法中根据需要编写自己的鉴权业务,wx.uploadFile根据自己后台上传接口更改
const COM = require("config.js");
let baseUrl = '';
if (COM.active === 'dev') {
baseUrl = COM.devservice;
} else {
baseUrl = COM.proservice;
}
function getHeader(method, url) {
let header = {
'content-type': 'application/x-www-form-urlencoded'
};
header['Token'] = '';
return header;
}
const http = ({
url = '',
param = {},
...other
} = {}) => {
let timeStart = Date.now();
return new Promise((resolve, reject) => {
wx.request({
url: getUrl(url),
data: param,
header: getHeader("POST", url),
...other,
complete: (res) => {
console.log(`耗时${Date.now() - timeStart}`);
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(res.data)
} else if (res.statusCode >= 500) {
//token过期 验证失败
console.log("请求失败" + res.message)
resolve(res.data);
} else {
console.log(res)
reject(res)
}
}
})
})
}
const upload = ({
url = '',
imgUrl = ''
}) => {
let timeStart = Date.now();
return new Promise((resolve, reject) => {
wx.uploadFile({
url: getUrl(url), //开发者服务器地址
header: getHeader("POST", url),
filePath: imgUrl, //要上传文件资源的路径
name: "imgfile", //文件对应的 key,开发者在服务端可以通过这个 key 获取文件的二进制内容
success: (res) => {
console.log(`耗时${Date.now() - timeStart}`);
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(JSON.parse(res.data))
} else if (res.statusCode >= 500) {
//token过期 验证失败
console.log("请求失败" + res.message)
resolve(JSON.parse(res.data));
} else {
console.log(res)
reject(res)
}
},
fail:function(e){
console.log("请求失败" + e.errMsg)
resolve(e);
}
})
})
}
const getUrl = (url) => {
if (url.indexOf('://') == -1) {
url = baseUrl + url;
}
return url
}
// get方法
const get = (url, param = {}) => {
return http({
url,
param
})
}
const post = (url, param = {}) => {
return http({
url,
param,
method: 'post'
})
}
const wxupload = (url, imgUrl) => {
return upload({
url,
imgUrl,
})
}
module.exports = {
get,
post,
wxupload,
}
config.js作为参考
const account = 'gh_d644a206c41d';
const token = 'ZTc0ZjRiOGI0NGNmNDY2NDk3ZDU1NDUyZmU0NTljMTk3NzZiN2M5MS0wYzUzLTBmNDktMDQ1Mi0zYTFkMWUxNGFiYTM#';
const active = 'pro';
const devservice = 'http://192.168.0.134:8012/xcloud-api/';
const proservice = 'https://test.xcloud.com/xcloud-api/';
module.exports = {
account: account,
token:token,
active: active,
devservice: devservice,
proservice: proservice
}
api.js为你小程序需要调用的后台接口列表 这里仅供参考
let HTTP = require("http.js");
/**
* 获取微信小程序授权参数
* @param p(code,account)
* @returns {*}
*/
export const getWeixinSmallOAuthMessage = p => HTTP.post('wechat/v1/getWeixinSmallOAuthMessage.json', p);
/**
* 授权小程序获取手机号码
* @param p(sessionKey,encrypted,iv)
* @returns {*}
*/
export const getSmallAppPhone = p => HTTP.post('wechat/v1/getSmallAppPhone.json', p);
/**
* 下载微信上传图片
* @param p(imgfile)
* @returns {*}
*/
export const wechaUploadImg = p => HTTP.wxupload('wechat/v1/ossUpload.json', p);
/**
* OSS对象存储
* @param p(imgfile)
* @returns {*}
*/
export const ossUpload = p => HTTP.post('wechat/v1/ossUpload.json', p);
module.exports = {
getWeixinSmallOAuthMessage: getWeixinSmallOAuthMessage,
getSmallAppPhone: getSmallAppPhone,
wechaUploadImg:wechaUploadImg,
ossUpload: ossUpload
}
接下来示例普通接口调用和上传图片调用
普通调用在调用之前引入配置 let API = require("../../utils/api.js");
//发起网络请求
API.getWeixinSmallOAuthMessage({
code: res.code,
account: COM.account,
}).then(res2 => {
//获取到用户凭证 存儲 3rd_session
const json = JSON.stringify(res2.data)
wx.setStorage({
key: "third_Session",
data: json
})
wx.setStorage({
key: "session_key",
data: res2.data.session_key
})
wx.setStorage({
key: "openid",
data: res2.data.openid
})
})
上传图片调用在调用之前引入配置 let API = require("../../utils/api.js");
根据自己的上传业务调整
onChoicePhotoHandle() {
wx.showActionSheet({
itemList: ["拍照","从手机相册选择"],
success: function(res) {
console.log("选择的是 :", res.tapIndex);
let sourceType = "camera";
if (res.tapIndex == 0) {
sourceType = "camera"; //相机
} else if (res.tapIndex == 1) {
sourceType = "album"; //相册
}
wx.chooseImage({
count: 3,
sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图,默认二者都有
sourceType: [sourceType],
success: function(res) {
wx.showLoading({
title: '上传中...'
})
var tempFilePaths = res.tempFilePaths;
for (var i = 0; i < tempFilePaths.length; i++) {
that.wechaUploadImg(tempFilePaths[i]);
}
}
});
},
fail: function(res) {
console.log(res.errMsg);
}
});
},
wechaUploadImg: function (imgUrl) {
that = this;
API.wechaUploadImg(imgUrl).then(res => {
wx.hideLoading();
if(res.success){
that.setData({
imglist: that.data.imglist.concat(res.data.imgPath)
});
}else{
wx.showToast({
title: '上传失败',
icon: 'none',
duration: 1500
})
}
})
},