小程式有關的網絡方面的API隻有:
普通 HTTPS 請求(wx.request)、上傳檔案(wx.uploadFile)、下載下傳檔案(wx.downloadFile) 和 WebSocket 通信(wx.connectSocket)
- wx.request
wx.request({
url: 'https://www.baidu.com', // 僅為示例,并非真實的接口位址
method: 'POST',
data: { //添加參數 json類型
parm1: '',
parm2: ''
},
header: {
'content-type': 'application/json' // 預設值
},
success(res) { //傳回結果
console.log(res.data)
},
fail(err){
console.log(err)
},
complete: function(res) {
console.log('complete後的res資料:')
}
})
//如果需要終止請求:
//原示例
const requestTask = wx.request({
})
requestTask.abort() // 取消請求任務
值 | 說明 |
---|---|
OPTIONS | HTTP 請求 OPTIONS |
GET \ PUT \ DELETE \POST | HTTP 請求方法 |
請求method可以根據需要做資訊配置。
- wx.uploadFile
關于上傳檔案,比如頭像上傳:
setImage:function(e){
var _this = this
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
var tempFilePaths = res.tempFilePaths
console.log(tempFilePaths)
wx.uploadFile({
url: “https://www.baidu.com",
filePath: tempFilePaths[0],
name: 'uploadFile',
formData: {
'userId': XX
},
success: function (res) {var data = JSON.parse(res.data) //與wx.request不同,wx.uploadFile傳回的是[字元串],需要自己轉為JSON格式
console.log('上傳成功')
_this.setData({ //wx.uploadFile本身有一個this,是以要通過外部var _this = this 把this帶進來
headerImageUrl: data.headerImageUrl
})
console.log('重新整理成功')
}
})
}
})
},
//同1,如果終止上傳,或者檢視進度可以
uploadTask.onProgressUpdate((res) => {
console.log('上傳進度', res.progress)
console.log('已經上傳的資料長度', res.totalBytesSent)
console.log('預期需要上傳的資料總長度', res.totalBytesExpectedToSend)
})
uploadTask.abort() // 取消上傳任務
- wx.downloadFile
const downloadTask = wx.downloadFile({
url: 'https://www.baidu.com', // 僅為示例,并非真實的資源
success(res) {
// 隻要伺服器有響應資料,就會把響應内容寫入檔案并進入 success 回調,業務需要自行判斷是否下載下傳到了想要的内容
if (res.statusCode === 200) {
var tempFilePath = res.tempFilePath
//console.log('臨時檔案位址是:' + tempFilePath)
wx.saveFile({
tempFilePath: tempFilePath,
success: function(res) {
var saveFilePath = res.savedFilePath
},//可以将saveFilePath寫入到頁面資料中
fail: function(res) {},
complete: function(res) {
console.log('complete後的res資料:')
},
},
fail: function(res) {
wx.showModal({
title: '下載下傳失敗',
content: 'xxx',
})
},
complete: function(res) {},
}
})
downloadTask.onProgressUpdate((res) => {
console.log('下載下傳進度', res.progress)
console.log('已經下載下傳的資料長度', res.totalBytesWritten)
console.log('預期需要下載下傳的資料總長度', res.totalBytesExpectedToWrite)
})
downloadTask.abort() // 取消下載下傳任務
-
WebSocket
暫時還沒用到,後續再補