Skip to content

Instantly share code, notes, and snippets.

@raymondzhaoy
Forked from song940/app.js
Created August 28, 2018 05:46
Show Gist options
  • Save raymondzhaoy/66d1f373522c76b7fbe2bd02c8c46e11 to your computer and use it in GitHub Desktop.
Save raymondzhaoy/66d1f373522c76b7fbe2bd02c8c46e11 to your computer and use it in GitHub Desktop.
微信小程序 wx.request 封装
App({
/**
* [request description]
* @param {[type]} method [description]
* @param {[type]} url [description]
* @param {[type]} data [description]
* @param {[type]} header [description]
* @return {[type]} [description]
*/
request: function(method, url, data, header){
if(typeof method === 'object'){
url = method.url;
data = method.data;
header = method.header;
method = method.method;
}
var req = {
method: method,
url : url,
header: {},
data : {}
}, def = {
header: function(name, value){
if(value) req.header[ name ] = value;
else req.header = name;
return def;
},
query: function(name, value){
if(value) req.data[ name ] = value;
else req.data = name;
return def;
},
send: function(name, value){
if(value) req.data[ name ] = value;
else req.data = name;
return def;
},
use: function(middleware){
req = middleware.call(def, req);
return def;
},
end: function(callback, done){
var p = new Promise(function(accept, reject){
if(!callback){
wx.showNavigationBarLoading();
callback = function(err, res){
wx.hideNavigationBarLoading();
if(err) return reject(err);
else accept(res);
};
}
});
if(!req.header['content-type']){
req.header['content-type'] = req.method == 'get' ?
'application/x-www-form-urlencoded' : 'application/json';
}
req.complete = done;
req.fail = callback;
req.success = callback.bind(req, null);
wx.request(req);
return p;
}
};
'get post put delete'.split(' ').forEach(function(method){
def[ method ] = (function(){
return function(url){
req.url = req.url || url;
req.method = req.method || method;
return def;
};
})();
});
return def;
}
});
const app = getApp();
Page({
data: {
list: [],
},
onLoad: function () {
var self = this;
app.request()
.get('https://api.lsong.org/ip/all')
.query({ name: 'test' })
.end()
.then(function(res){
self.setData({ list: res.data });
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment