小程序封裝wx.request,以及調用


1、新建一個api目錄,與pages同級

2、在api目錄下新建一個api.js文件

3、編寫代碼

const host = 'http://test.test.cn'
const wxRequest = function (params, url) {
  wx.showToast({
    title: '加載中...',
    icon: 'loading'
  })
  wx.request({
    url: url,
    method: params.method || 'GET',
    data: params.data || {},
    header: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    },
    success: function (res) {
      params.success && params.success(res)
      wx.hideToast()
    },
    fail: function (res) {
      params.fail && params.fail(res)
    },
    complete: function (res) {
      params.complete && params.complete(res)
    }
  })
}

const bindCode = function (params) { wxRequest(params, host + '/AppPhone/Api') }
const startScan = function (params) { wxRequest(params, host + '/AppPhone/Api') }
const imgToservers =  function (params) { wxRequest(params, host + '/AppPhone/Api/upload_files') }

module.exports = {
  bindCode,
  startScan,
  imgToservers
}

4、在js中調用

import api from '../../api/api.js'
Page({

  /**
   * 頁面的初始數據
   */
  data: {
    shopCode: '',
    deviceId: '',
  },

  /**
   * 生命周期函數--監聽頁面加載
   */
  onLoad: function (options) {
    var getShopInfo = wx.getStorageSync('shopInfo');
    if (getShopInfo) {
      this.setData({
        shopCode: getShopInfo.shop_code,
        deviceId: getShopInfo.device_id
      })
    }else{
      wx.redirectTo({
        url: '../bindnum/bindnum?type=1'
      })
    }
  },
  beginScan: function(){
    var _that = this;
    api.startScan({ method: 'POST', data: { shop_code: this.data.shopCode, device_id: this.data.deviceId, method: 'get_phone_scanner_id' }, success: function(res){ console.log(res.data); } });
  },
})

5、問題

一開始wx.request中header設置為

header: {
    'content-type': 'application/json' // 默認值
},
導致接口調用時,報500

后面查找發現,終於找到了解決方案,將header設置為:
  header: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
  },

就可以成功調用了

 

參考文章: wx.request發送與服務端接受

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM