1、微信小程序wx.request()#
微信小程序請(qǐng)求服務(wù)接口API的方法,這里不再累述,具體看官方文檔“https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-request.html#wxrequestobject”
wx.request發(fā)起的是 HTTPS 請(qǐng)求。
2母蛛、服務(wù)API請(qǐng)求封裝#
這里封裝的是POST請(qǐng)求方式翩剪,GET請(qǐng)求一樣乳怎。
在utils下創(chuàng)建httpcommon.js文件,方法如下:
// Ajax接口請(qǐng)求
function wxAjax(url, postData, doSuccess, doFail, doComplete) {
wx.request({
url: getApp().config.api_host + url,
data: postData,
method: 'POST',
success: function (res) {
if (typeof doSuccess == "function") {
doSuccess(res);
}
},
fail: function () {
if (typeof doFail == "function") {
wx.showToast({
title: '網(wǎng)絡(luò)異常',
icon: 'success',
duration: 2000
});
doFail();
}
},
complete: function () {
if (typeof doComplete == "function") {
doComplete();
}
}
})
}
module.exports = {
wxAjax: wxAjax
}
在app.js文件中增加如下配置:
//全局配置信息
config: {
api_host: "http://127.0.0.1:8888"
}
服務(wù)API調(diào)用使用示例如下:
//app.js
var common = require('utils/common.js');
App({
onLaunch: function () {
var that = this;
that.login();
},
//登錄
login: function (cb) {
var that = this;
wx.login({
success: function (res) {
var code = res.code;
var parmptLogin = { "code": code};
common.wxAjax("/login/login", JSON.stringify(para), that.successLogin)
}
})
},
successLogin:function(res){
// todo
}
});