http
优质
小牛编辑
147浏览
2023-12-01
request(option)
发起http请求
option 请求选项
属性 | 类型 | 说明 |
---|---|---|
url | string | 请求URL,必填参数 |
method | string | 请求方法,默认"GET" |
headers | Object | 请求头,字符串键值对 |
body | string/ArrayBuffer | 请求体,string或ArrayBuffer类型 |
success | function | 请求成功回调,成功仅代表HTTP请求完成,不等同于请求成功200 |
fail | function | 请求失败回调,如连接超时等网络错误 |
complete | function | 请求结束回调,无论请求成功失败都会调用 |
uploadProgress | function | 上传进度回调 |
downloadProgress | function | 下载进度回调 |
option.success 分享成功回调参数
属性 | 类型 | 说明 |
---|---|---|
statusCode | number | 响应码 |
headers | object | 响应头,字符串键值对 |
text | function | 以字符串形式读取响应体 |
arrayBuffer | function | 以ArrayBuffer形式读取响应体, 请求发生错误时返回大小为0的ArrayBuffer |
jsonObject | function | 以JSON对象形式读取响应体,已经经过JSON.parse解析, 请求发生错误或响应体为空时返回null |
option.fail 请求失败回调函数参数
属性 | 类型 | 说明 |
---|---|---|
msg | string | 错误原因,用于调试,不适合直接展示给用户 |
option.uploadProgress 上传进度回调函数参数
属性 | 类型 | 说明 |
---|---|---|
curr | number | 当前进度 |
total | number | 总进度 |
option. downloadProgress 下载进度回调函数参数
属性 | 类型 | 说明 |
---|---|---|
curr | number | 当前进度 |
total | number | 总进度,响应头无Content-Length时为-1 |
示例
BK.Http.request({
url: 'https://httpbin.org/anything?key=value',
method: 'POST',
headers: {
'Referer': 'https://hudong.qq.com',
'User-Agent': 'brick-client',
'Content-Type': 'application/json'
},
body: JSON.stringify({ "key": "value" }),
success: function (succObj) {
console.log('statusCode', succObj.statusCode);
console.log('headers', JSON.stringify(succObj.headers));
const bodyStr = succObj.text();
console.log('body', bodyStr);
},
fail: function (errObj) {
console.log('error', errObj.msg);
},
complete: function () {
console.log('complete');
},
uploadProgress: function (curr, total) {
console.log('upload progress', curr / total);
},
downloadProgress: function (curr, total) {
console.log('download progress', curr / total);
}
});