微信小程序API 发起请求

上传时间:2018-06-14阅读数:1495

wx.request(OBJECT)


OBJECT参数说明:

参数名类型必填说明
urlString开发者服务器接口地址
dataObject、String请求的参数
headerObject设置请求的 header , header 中不能设置 Referer
methodString默认为 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
dataTypeString默认为 json。如果设置了 dataType 为 json,则会尝试对响应的数据做一次 JSON.parse
successFunction收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'}
failFunction接口调用失败的回调函数
completeFunction接口调用结束的回调函数(调用成功、失败都会执行)

success返回参数说明:

参数类型说明最低版本
dataObject/String/ArrayBuffer开发者服务器返回的数据
statusCodeNumber开发者服务器返回的 HTTP 状态码
headerObject开发者服务器返回的 HTTP Response Header1.2.0
data 数据说明 最终发送给服务器的数据是 String 类型,如果传入的 data 不是 String 类型,会被转换成 String 。转换规则如下:
  • 对于 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

  1. tip: content-type 默认为 'application/json'
  2. bug: 开发者工具0.10.102800版本,headercontent-type设置异常;
  3. tip: 客户端的 HTTPS TLS 版本为1.2,但Android的部分机型还未支持 TLS 1.2,所以请确保 HTTPS 服务器的 TLS 版本支持1.2及以下版本;
  4. tip: 要注意 method 的 value 必须为大写(例如:GET);
  5. tip: url 中不能有端口;
  6. tip: request 的默认超时时间和最大超时时间都是 60s
  7. tip: request 的最大并发数是 5
  8. tip: 网络请求的 referer 是不可以设置的,格式固定为 https://servicewechat.com/{appid}/{version}/page-frame.html,其中{appid}为小程序的 appid,{version}为小程序的版本号,版本号为 0 表示为开发版。
目录