小程序模板网

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

发布时间:2017-12-29 18:18 所属栏目:小程序开发教程

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

 
 
 

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

 

		
  1. var HOST = 'http://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值进一步判断,特定错误码统一处理,比如跳转登录页面等。



易优小程序(企业版)+灵活api+前后代码开源 码云仓库:starfork
本文地址:https://www.eyoucms.com/wxmini/doc/course/18316.html 复制链接 如需定制请联系易优客服咨询:800182392 点击咨询
QQ在线咨询