微信小程序wx.request接口
阿新 • • 發佈:2018-11-07
file scope tex alt bin connect setting roc 用戶
微信小程序wx.request接口
wx.request是小程序客戶端與服務器端交互的接口
HTTPS 請求
一個微信小程序,只能同時(同時不能大於5個)有5個網絡請求
wx.request(OBJECT)
發起網絡請求
url
data
header
method
dataType
wx.request({ url: 'test.php', //僅為示例,並非真實的接口地址 data: { x: '' , y: '' }, header: { 'content-type': 'application/json' // 默認值 }, success: function(res) { console.log(res.data) } })
四種網絡請求:
(wx.request)
(wx.uploadFile)
(wx.downloadFile)
(wx.connectSocket)
var request = {
url: '',
data: {},
method: '',
success: function (res) {
},
fail: function () {
},
complete: function () {
}
}
wx.openSetting 來跳轉到設置授權界面
/* index.js */ // 若有用戶信息存在則繼續 Page({ onLoad () { wx.getStorage({ key: 'userinfo', success: (res) => { this.setUserinfo(res) }, fail: (res) => { api.login().then((res) => { this.setUserinfo(res) }).catch(e => { if (e.errMsg && e.errMsg === 'getUserInfo:fail auth deny') { this.setData({ isauth: false }) } }) } }) }, toSetting() { wx.openSetting({ success: (res) => { this.setData({ isauth: res.authSetting['scope.userInfo'] }) if (res.authSetting['scope.userInfo']) { api.login().then((res) => { this.setUserinfo(res) }) } } }) } }) // setUserinfo 就是對用戶信息做一下處理 不具體展開了 /* index.wxml */ <view class="unauth" wx:if="{{!isauth}}"> <image class="unauth-img" src="../../images/auth.png"></image> <text class="unauth-text">檢查到您沒打開授權</text> <button class="color-button unauth-button" bindtap="toSetting">去設置</button> </view> <view class="container" wx:else> ... </view>
function queryRequest(data){ wx.request({ url:"https://example.com/api/", data:data, header:{ // "Content-Type":"application/json" }, success:function(res){ console.log(res.data) }, fail:function(err){ console.log(err) } }) }
服務器設置:
上傳文件
// Content-type為multipart/form-data
function uploadFile(file,data) {
wx.uploadFile({
url: 'http://example.com/upload',
filePath: file,
name: 'file',
formData:data,
success:function(res){
console.log(res.data)
},
fail:function(err){
console.log(err)
}
})
}
下載文件
function downloadFile(url,typ,success){
wx.downloadFile({
url:url,
type:type,
success:function(res){
if(success){
success(res.tempFilePath)
}
},
fail:function(err){
console.log(err)
}
})
}
function svaeFile(tempFile,success){
wx.saveFile({
tempFilePath:tempFile,
success:function(res){
var svaedFile=res.savedFilePath
if(success){
success(svaeFile)
}
}
})
}
微信小程序wx.request接口