微信小程序封裝http訪問網絡庫實例代碼

以前都是使用LeanCloud爲存儲,如今用傳統API調用時作以下封裝php

複製代碼
var HOST = 'http://localhost/lendoo/public/index.php/';
// 網站請求接口,統一爲post
function post(req) { 
//發起網絡請求
 wx.request({
 url: HOST + req.uri, 
 data: req.param, 
 header: {
   "content-type": "application/x-www-form-urlencoded"
 },
 method: 'POST', 
 success: function (res) {
  req.success(res.data)
 }, 
 fail: function (res) {
   console.log(res);
 }
 })
}
// 導出模塊
module.exports = { post: post
}
複製代碼

而後前端調用就能夠這樣作了:前端

複製代碼
var http = require('../../utils/http.js');
...
 http.post({ 
  uri: http.orderListUri, 
  param: {
   third_session: wx.getStorageSync('third_session')
  },  
   success: function (data) {
   that.setData({
    orderList: data
  });
  }
 });
複製代碼

通常對本身寫的接口給本身用的時候,method方法或header都是約定好的,因此不用重複書寫。網絡

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

而fail回調方法也能夠統一處理;進一步地,也能夠對success回調裏的針對code值進一步判斷,特定錯誤碼統一處理,好比跳轉登陸頁面等。session

相關文章
相關標籤/搜索