小程序封裝wx.request
const app = getApp()
const request = (url, options, headers = "application/json; charset=UTF-8") => {
return new Promise((resolve, reject) => {
wx.request({
url: `${app.globalData.host}${url}`,
method: options.method,
data: options.data ,
header: {
'Content-Type': headers
},
success(request) {
console.log(request);
if (request.data.status === 1) {
resolve(request.data)
} else {
reject(request.data)
}
},
fail(error) {
reject(error.data)
}
})
})
}
const get = (url, options = {}) => {
return request(url, { method: 'GET', data: options })
}
const post = (url, options, headers) => {
return request(url, { method: 'POST', data: options}, headers)
}
module.exports = {
get,
post,
}
引用api
import api from '../../api/api';
api.post("http://xxxx", {
code,
encryptedData: res.encryptedData,
iv: res.iv,
}, "application/x-www-form-urlencoded")
.then(res => {
app.globalData.openid = res.data.openId;
}).catch(err => {
wx.showModal({
title: '提示',
content: '注冊(cè)失敗',
})
})
封裝wx.uploadFile:
function uploadFile(url, param){
return new Promise((resolve, reject) => {
const app = getApp();
wx.uploadFile({
url: app.globalData.host + url,
header: {
'content-type': 'application/x-www-form-urlencoded'
},
name: 'file',
success(result) {
console.log(result);
const res = JSON.parse(result.data);
res.status === -1 ? reject(res) : resolve(res);
},
fail(error){
const err = JSON.parse(error.data);
reject(err);
},
...param,
})
})
}