微信小程序-網(wǎng)絡(luò)請求

程序開發(fā)中難免要與后臺進(jìn)行交互,今天我們就來說一說,微信小程序中的網(wǎng)絡(luò)請求

我們通過 wx.request(object)來進(jìn)行網(wǎng)絡(luò)請求,下面我們看下object 中有哪些參數(shù)

16562265-9C9B-41B9-8590-F591E75E26FE.png

看看他的用法,上代碼

CCB63E3C-D641-4F3F-8083-48E09557B6D3.png

下面是來自,官方文檔的一些注意事項(xiàng)
1)data

1.data 數(shù)據(jù)說明 最終發(fā)送給服務(wù)器的數(shù)據(jù)是 String 類型,
如果傳入的 data 不是 String 類型,會被轉(zhuǎn)換成 String 。轉(zhuǎn)換規(guī)則如下:

對于 header['content-type'] 為 'application/json' 的數(shù)據(jù),會對數(shù)據(jù)進(jìn)行 JSON 序列化

對于 header['content-type'] 為 'application/x-www-form-urlencoded' 的數(shù)據(jù),會將數(shù)據(jù)轉(zhuǎn)換成 query string (encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)...)

2).method

    1.默認(rèn)為 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT

    2.值必須為大寫

3) header

1.header 為 application/json,接口傳回來的參數(shù)要是json 格式的,
否則會報(bào)500錯誤,比如我接口返回來的參數(shù)是xml則header['content-type'] 
要設(shè)置為'application/x-www-form-urlencoded'

接下來我們可以封裝一個自己的request 請求
創(chuàng)建一個request.js 文件,代碼如下

var rootDocment = 'hxxxxx';//你的域名  
function req(url,data,cb){  
    wx.request({  
      url: rootDocment + url,  
      data: data,  
      method: 'post',  
      header: {'Content-Type': 'application/json'},  
      success: function(res){  
        return typeof cb == "function" && cb(res.data)  
      },  
      fail: function(){  
        return typeof cb == "function" && cb(false)  
      }  
    })  
}  
  
  
module.exports = {  
  req: req  
}  

其中module.exports是將req方法暴露出去使得別的文件中可以使用該方法,由于js函數(shù)是異步執(zhí)行的,所以return 的是回調(diào)函數(shù),而不是具體的數(shù)據(jù)

為了其他文件方便調(diào)用此方法,我們在根目錄的app.js文件中將其注冊成為全局函數(shù),如下

//app.js

var http = require('../../request.js')  
App({
  onLaunch: function () {
    //調(diào)用API從本地緩存中獲取數(shù)據(jù)
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },
  getUserInfo:function(cb){
    var that = this
    if(this.globalData.userInfo){
      typeof cb == "function" && cb(this.globalData.userInfo)
    }else{
      //調(diào)用登錄接口
      wx.login({
        success: function () {
          wx.getUserInfo({
            success: function (res) {
              that.globalData.userInfo = res.userInfo
              typeof cb == "function" && cb(that.globalData.userInfo)
            }
          })
        }
      })
    }
  },
  globalData:{
    userInfo:null
  },
 func:{  
    req:http.req  
  } 
})

這時這個req就是全局的了,在調(diào)用時我們可以使用getApp.func.req()來調(diào)用,具體如下

var app = getApp()  
Page({  
  data: {  
      
  },  
  onLoad: function (opt) {  
    //console.log(opt.name)  
   app.func.req('/api/get_data',{},function(res){  
     console.log(res)  
    });  
  }  
})  
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容