在上一家公司的时候写的微信小程序相关的网络请求方法,做了一些简单的封装,今天共享出来
js请求工具类的封装http.js,包含了get,post方法:
var appUrl = 'https://127.0.0.1:8080/';
/**
*基础的网络请求
*/
function requestGet(requestData, finish) {
console.log(" GET request=" + JSON.stringify(requestData) + " url=" + (url + requestData.method))
var token = wx.getStorageSync("token");
console.log(" token=" + token)
wx.request({
url: appUrl + requestData.method,
data: requestData.data,
method: 'GET',
header: {
"Content-Type": "application/json",
"Access-User-Token": token,
},
success: function(res) {
finish(res.data)
},
fail: function(res) {
finish(res)
},
complete: function() {
}
})
}
function requestPost(requestData, finish) {
console.log(" POST request=" + JSON.stringify(requestData))
var token = wx.getStorageSync("token");
console.log(" token=" + token)
wx.request({
url: appUrl + requestData.method,
data: requestData.data,
method: 'POST',
header: {
"Content-Type": "application/json",
"Access-User-Token": token,
},
success: function(res) {
finish(res.data)
},
fail: function(res) {
finish(res)
},
complete: function() {
}
})
}
/**
- 以下为业务逻辑的网络请求
*/
/**
- 登录凭证校验
*/
function excuteCode2Session(param) {
var data = param.data
requestGet(data, function(res) {
param.finish(res)
})
}
module.exports.excuteCode2Session = excuteCode2Session;
js中引入http.js使用
server.excuteCode2Session({
data: {
method: "auth_code2Session",
data: {
js_code: code,
userInfo: userInfo
},
},
finish: function(res) {
var openid = res.data.openid;
var token = res.data.token;
}
})
文件上传可以利用微信自带的api,参数type包含:
video 选择了视频文件
image 选择了图片文件
file 选择了除图片和视频的文件
wx.chooseMessageFile({
count: 10,
type: 'image',
success (res) {
const tempFilePaths = res.tempFilePaths
wx.uploadFile({
url: 'https://127.0.0.1:8080//upload', //仅为示例,非真实的接口地址
filePath: tempFilePaths[0],
name: 'file',
formData: {
'user': 'test'
},
success (res){
const data = res.data
//do something
}
})
}
})