wx.request
//采用get方式
wx.request({
url:'http://test.com/getInfo?id=1&version=1.0.0',
success:function(res){
console.log(res)//服务器返回信息
}
})
//通过data参数传递数据
wx.request({
url:'https://test.com/getInfo',
data:{
id:1,
version:'1.0.0'
},
success:function(res){
console.log(res)//服务器返回信息
}
})
//请求的包体为{"a":{"b":[1,2,3],"c":{"d":"test"}}}
wx.request({
url = 'https://test.com/postInfo',
method:'post',
header:{'content-type':'application/json'},
data:{
a:{
b:[1,2,3],
c:{d:"test"}
}
},
success:function(res){
console.log(res)//服务器返回信息
}
})
参数名 | 类型 | 必填 | 默认值 | 描述 |
---|---|---|---|---|
url | String | 是 | 开发者服务器接口地址 | |
data | Object/String | 否 | 请求的参数 | |
header | Object | 否 | 设置请求的 header,header 中不能设置 Referer,默认header['content-type'] = 'application/json' | |
method | String | 否 | GET | (需大写)有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT |
dataType | String | 否 | json | 回包的内容格式,如果设为json,会尝试对返回的数据做一次 JSON解析 |
success | Function | 否 | 收到开发者服务成功返回的回调函数,其参数是一个Object | |
fail | Function | 否 | 接口调用失败的回调函数 | |
complete | Function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
小程序环境要求request发起的网络请求必须是https协议请求, wx.request请求的域名需要在小程序管理平台进行配置,如果小程序正式版使用未配置的域名,在控制台会有相应的报错。为方便开发调试,开发者工具、小程序的开发版和小程序的体验版在某些情况下允许请求任意域名。
wx.request发送请求后,服务器处理请求并返回HTTP包,小程序端收到返回信息会触发success回掉,同时回调会带上一个Object信息。
参数名 | 类型 | 描述 |
---|---|---|
data | Object/String | 开发者服务器返回的数据 |
statusCode | Number | 开发者服务器返回的 HTTP 状态码 |
header | Object | 开发者服务器返回的 HTTP Response Header |
1.设置超时时间
小程序默认超时时间是60秒,在小程序根目录里面的app.json可以指定request的超时时间
{
"networkTimeout":{
"request":10000 //设置接口请求超时时间为10秒
}
}
var isRequest = false;
Page({
tap:function(){
if(isRequest)
return
}
isRequest = true
wx.showLoading()
wx.request({
url:'https://test.com/getInfo',
method:'POST',
header:{'conyent-type':'applocation/json'},
data:{},
success:function(res){
if(res.statusCode === 200){
console.log(res.data)//服务器返回信息
}
}
fail:function(res){
wx.showToast({title:'系统错误'})
isRequest = false
}
complete:function(res){
wx.hideLoading()
isRequest = false
}
})
})