好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

微信小程序设置https请求的步骤详解

使用wx.request可以发起一个http请求,一个微信小程序被限制为同时只有5个网络请求。

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)
 }

 })

}

上面的代码会发送一个http get请求,然后打印出返回的结果。其中的参数也比较容易理解。

    url 服务器的url地址

    data 请求的参数可以采用String data:"xxx=xxx&xxx=xxx"的形式或者Object data:{"userId":1}的形式

    header 设置请求的header

    success 接口成功的回调

    fail 接口失败的回调

另外还有两个参数没有在代码里:

     method http的方法,默认为GET请求

     complete 调用接口结束之后的回调,无论成功或者失败该接口都会被调用

上传文件

上传文件的api为wx.uploadFile,该api会发起一个http post请求,其中的Content-typemultipart/form-data。服务器端需要按照该Content-type类型接收文件,示例代码:

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)
 }

 })

}

下载文件的api为wx.downloadFile,该api会发起一个http get请求,并在下载成功之后返回文件的临时路径,示例代码:

function downloadFile(url,typ,success){
 wx.downloadFile({
 url:url,
 type:typ,
 success:function(res){
 if(success){
 success(res.tempFilePath)
 }
 },
 fail:function(err){
 console.log(err)
 }
 })
}

其中的url,header,fail,completewx.uploadFile的参数使用是一致的,其中有区别的参数是:

     type:下载资源的类型,用于客户端自动识别,可以使用的参数image/audio/video

     success:下载成功之后的回调,以tempFilePath的参数返回文件的临时目录:res={tempFilePath:'文件路径'}

下载成功后的是临时文件,只会在程序本次运行期间可以使用,如果需要持久的保存,需要调用方法wx.saveFile主动持久化文件,实例代码:

function svaeFile(tempFile,success){
 wx.saveFile({
 tempFilePath:tempFile,
 success:function(res){
 var svaedFile=res.savedFilePath
 if(success){
 success(svaeFile)
 }
 }
 })
}

可以在app.js中设置networkTimeout可以设置四种类型网络访问的超时时间:

"networkTimeout":{
 "request": 10000,
 "connectSocket": 10000,
 "uploadFile": 10000,
 "downloadFile": 10000
}

查看更多关于微信小程序设置https请求的步骤详解的详细内容...

  阅读:11259次