欢迎光临,了解微信小程序开发,就上易用通!

微信小程序封装http访问网络库实例代码

发布:2017-12-29 18:18浏览: 来源:网络 作者:tianshu

之前都是使用LeanCloud为存储,现在用传统API调用时做如下封装var HOST = 'https://localhost/lendoo/public/index.php/';// 网站请求接口,统一为postfunction post(req) { //发起网络请求 wx.request({ url: HOST + ...

 
 
 

之前都是使用LeanCloud为存储,现在用传统API调用时做如下封装

 

		
  1. var HOST = 'https://localhost/lendoo/public/index.php/';
  2. // 网站请求接口,统一为post
  3. function post(req) {
  4. //发起网络请求
  5. wx.request({
  6. url: HOST + req.uri,
  7. data: req.param,
  8. header: {
  9. "content-type": "application/x-www-form-urlencoded"
  10. },
  11. method: 'POST',
  12. success: function (res) {
  13. req.success(res.data)
  14. },
  15. fail: function (res) {
  16. console.log(res);
  17. }
  18. })
  19. }
  20. // 导出模块
  21. module.exports = { post: post
  22. }

然后前端调用就可以这样做了:

 

		
  1. var http = require('../../utils/http.js');
  2. ...
  3. http.post({
  4. uri: http.orderListUri,
  5. param: {
  6. third_session: wx.getStorageSync('third_session')
  7. },
  8. success: function (data) {
  9. that.setData({
  10. orderList: data
  11. });
  12. }
  13. });

一般对自己写的接口给自己用的时候,method方法或header都是约定好的,所以不用重复书写。

 

		
  1. 1 header: {
  2. 2 "content-type": "application/x-www-form-urlencoded"
  3. 3 },
  4. 4 method: 'POST'

而fail回调方法也可以统一处理;进一步地,也可以对success回调里的针对code值进一步判断,特定错误码统一处理,比如跳转登录页面等。






免责声明:本站所有文章和图片均来自用户分享和网络收集,文章和图片版权归原作者及原出处所有,仅供学习与参考,请勿用于商业用途,如果损害了您的权利,请联系网站客服处理。