Last active
August 28, 2018 05:46
-
-
Save lsongdev/43ce748ba578d40f3873997524f41e0d to your computer and use it in GitHub Desktop.
微信小程序 wx.request 封装
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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