小程序开放平台

文档中心
基础
路由
跳转
转发
界面
网络
发起请求
request
上传
下载
WebSocket
支付
数据缓存
媒体
位置
开放接口
设备
XHSML
性能
第三方平台
文件
数据分析
画布

xhs.request

开发
>
JS API
>
网络
>
发起请求
>
request
>
更新时间:2024-11-28 20:13:27

以Promise风格调用: 支持

发起 HTTPS 网络请求

参数

Object object

属性
类型
默认值
必填
说明
urlstring开发者服务器接口地址(推荐使用 encodeURIComponent 对参数部分进行编码)
datastring,object,ArrayBuffer请求的参数
headerobject设置请求的 header,header 中不能设置 Referer。content-type 默认为 application/json
timeoutnumber超时时间,单位为毫秒
methodstringHTTP 请求方法
dataTypestring返回的数据格式
responseTypestring响应的数据类型
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)

object.method 的合法值

说明
OPTIONSHTTP 请求 OPTIONS
GETHTTP 请求 GET
POSTHTTP 请求 POST
PUTHTTP 请求 PUT
DELETEHTTP 请求 DELETE

object.dataType 的合法值

说明
json返回的数据为 JSON,返回后会对返回的数据进行一次 JSON.parse
其他不对返回的内容进行 JSON.parse

object.responseType 的合法值

说明
text响应的数据为文本
arraybuffer响应的数据为 ArrayBuffer

object.success 回调函数

属性
类型
说明
datastring,object,Arraybuffer开发者服务器返回的数据
statusCodenumber开发者服务器返回的 HTTP 状态码
headerobject开发者服务器返回的 HTTP Response Header
cookiesarray开发者服务器返回的 cookies,格式为字符串数组

data参数说明

最终发送给服务器的数据是 String 类型,如果传入的 data 不是 String 类型,会被转换成 String 。转换规则如下:

  • 对于
    GET
    方法的数据,会将数据转换成 query string
    (encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)...)
  • 对于
    POST
    方法且
    header['content-type']
    application/json
    的数据,会对数据进行 JSON 序列化
  • 对于
    POST
    方法且
    header['content-type']
    application/x-www-form-urlencoded
    的数据,会将数据转换成 query string
    (encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)...)

实例代码

xhs.request({
  url: 'example.php', //仅为示例,并非真实的接口地址
  method: 'POST'
  data: {
    x: '',
    y: ''
  },
  header: {
    'content-type': 'application/json' // 默认值
  },
  success (res) {
    console.log(res.data)
  }
})