微信小程序API發起請求,wx.request發起請求
2017-12-22
導讀:wx.request(OBJECT) OBJECT參數說明: 參數名 類型 必填 說明 url String 是 開發者服務器接口地址 data Object、String 否 請求的參數 header Object 否 設置請求的 header , header 中不能設置 Referer method...
wx.request(OBJECT)
OBJECT參數說明:
參數名 | 類型 | 必填 | 說明 |
---|---|---|---|
url | String | 是 | 開發者服務器接口地址 |
data | Object、String | 否 | 請求的參數 |
header | Object | 否 | 設置請求的 header , header 中不能設置 Referer |
method | String | 否 | 默認為 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT |
dataType | String | 否 | 默認為 json。如果設置了 dataType 為 json,則會嘗試對響應的數據做一次 JSON.parse |
success | Function | 否 | 收到開發者服務成功返回的回調函數,res = {data: '開發者服務器返回的內容'} |
fail | Function | 否 | 接口調用失敗的回調函數 |
complete | Function | 否 | 接口調用結束的回調函數(調用成功、失敗都會執行) |
success返回參數說明:
參數 | 說明 | 最低版本 |
---|---|---|
data | 開發者服務器返回的數據 | |
statusCode | 開發者服務器返回的狀態碼 | |
header | 開發者服務器返回的 HTTP Response Header | 1.2.0 |
- 對于 header['content-type'] 為 'application/json' 的數據,會對數據進行 JSON 序列化
- 對于 header['content-type'] 為 'application/x-www-form-urlencoded' 的數據,會將數據轉換成 query string (encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)...)
示例代碼:
wx.request({
url: 'test.php', //僅為示例,并非真實的接口地址
data: {
x: '' ,
y: ''
},
header:{
"Content-Type":"application/json"
},
success: function(res) {
console.log(res.data)
}
})
返回值:
基礎庫 1.4.0 開始支持,低版本需做兼容處理
返回一個requestTask
對象,通過requestTask
,可中斷請求任務。
requestTask 對象的方法列表:
方法 | 參數 | 說明 | 最低版本 |
---|---|---|---|
abort | 中斷請求任務 | 1.4.0 |
示例代碼:
const requestTask = wx.request({
url: 'test.php', //僅為示例,并非真實的接口地址
data: {
x: '' ,
y: ''
},
header: {
'content-type': 'application/json'
},
success: function(res) {
console.log(res.data)
}
})
requestTask.abort() // 取消請求任務
Bug & Tip
-
tip
: content-type 默認為 'application/json' -
bug
: 開發者工具0.10.102800
版本,header
的content-type
設置異常; -
tip
: 客戶端的 HTTPS TLS 版本為1.2,但Android
的部分機型還未支持 TLS 1.2,所以請確保 HTTPS 服務器的 TLS 版本支持1.2及以下版本; -
tip
: 要注意 method 的 value 必須為大寫(例如:GET); -
tip
: url 中不能有端口; -
tip
: request 的默認超時時間和最大超時時間都是 60s -
tip
: request 的最大并發數是 5 -
tip
: 網絡請求的 referer 是不可以設置的,格式固定為 https://servicewechat.com/{appid}/{version}/page-frame.html,其中{appid}
為小程序的 appid,{version}
為小程序的版本號,版本號為 0 表示為開發版。
更多微信小程序開發教程,可以關注hi小程序。
第二部分:如何開通一個小商店
您可能感興趣: