小程序模板網(wǎng)

微信小程序封裝http訪問網(wǎng)絡(luò)庫實例代碼

發(fā)布時間:2017-12-29 18:18 所屬欄目:小程序開發(fā)教程

之前都是使用LeanCloud為存儲,現(xiàn)在用傳統(tǒng)API調(diào)用時做如下封裝var HOST = 'http://localhost/lendoo/public/index.php/';// 網(wǎng)站請求接口,統(tǒng)一為postfunction post(req) { //發(fā)起網(wǎng)絡(luò)請求 wx.request({ url: HOST + ...

 
 
 

之前都是使用LeanCloud為存儲,現(xiàn)在用傳統(tǒng)API調(diào)用時做如下封裝

 

		
  1. var HOST = 'http://localhost/lendoo/public/index.php/';
  2. // 網(wǎng)站請求接口,統(tǒng)一為post
  3. function post(req) {
  4. //發(fā)起網(wǎng)絡(luò)請求
  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. // 導(dǎo)出模塊
  21. module.exports = { post: post
  22. }

然后前端調(diào)用就可以這樣做了:

 

		
  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都是約定好的,所以不用重復(fù)書寫。

 

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

而fail回調(diào)方法也可以統(tǒng)一處理;進(jìn)一步地,也可以對success回調(diào)里的針對code值進(jìn)一步判斷,特定錯誤碼統(tǒng)一處理,比如跳轉(zhuǎn)登錄頁面等。



易優(yōu)小程序(企業(yè)版)+靈活api+前后代碼開源 碼云倉庫:starfork
本文地址:http://www.u-renovate.com/wxmini/doc/course/18316.html 復(fù)制鏈接 如需定制請聯(lián)系易優(yōu)客服咨詢:800182392 點擊咨詢
QQ在線咨詢
AI智能客服 ×