177-371-24501(同微信)

小程序简单封装http访问网络库

2022-04-21 管理员

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

文档出处:https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-request.html

代码如下:

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

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

  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. header: {
  2. "content-type": "application/x-www-form-urlencoded"
  3. },
  4. method: 'POST'

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

经过上述处理,是不是变得简洁了?

上一篇:微信小程序 生命周期函数解析
下一篇:微信小程序中如何使用WebSocket实现长连接(含完整源码)
相关资讯 Releva ntnews
解决方案 Solutions
相关热点 Hot spot
快速提升网站排名的方法
  1. 我们的优势
  2. 我们的实力
  3. 选择我们的理由
咨询电话(微信同号)

177-371-24501(同微信)

豫ICP备17049932号

Copyright © 2017-2022 版权所有 追风建站 Rights Reserved 技术支持:酷微科技

电话咨询 在线咨询 服务项目 SEO优化