tt.request
从基础库 1.0.0 开始支持,这是一个异步方法。
发起一个 HTTP 请求。网络相关的 API 在使用前需要配置域名白名单。请参考网络请求使用说明
参数
Object object
| 名称 | 数据类型 | 属性 | 默认值 | 描述 |
|---|---|---|---|---|
| url | string | required | N/A | 请求地址 |
| header | object | optional | {'content-type': 'application/json'}
|
请求 Header |
| method | string | optional | GET
|
请求方法 |
| data | object / string / arraybuffer | optional | null
|
请求数据 |
| dataType | string | optional | json
|
请求数据类型 |
| responseType | string | optional | text
|
响应数据类型,参数值可以是text或arraybuffer
|
| success | function | optional | 接口调用成功后的回调函数 | |
| fail | function | optional | 接口调用失败后的回调函数 | |
| complete | function | optional | 接口调用结束后的回调函数(调用成功、失败都会执行) |
object.method 的合法值
| 值 | 说明 |
|---|---|
| GET | |
| POST | |
| OPTIONS | |
| PUT | |
| HEAD | |
| DELETE |
object.dataType 的合法值
| 值 | 说明 |
|---|---|
| json | 返回的数据为 JSON,返回后会对返回的数据进行一次 JSON.parse |
| 其他 | 不对返回的内容进行 JSON.parse |
object.responseType 的合法值
| 值 | 说明 |
|---|---|
| text | 响应的数据为文本 |
| arraybuffer | 响应的数据为 ArrayBuffer |
object.success 回调函数
参数
Object res
| 名称 | 数据类型 | 描述 |
|---|---|---|
| statusCode | number | 返回 HTTP 状态码 |
| header | object | 返回 HTTP Header |
| data | object / string / arraybuffer | 返回数据 |
返回值
代码示例
let task = tt.request({
url: "someurl",
data: {
user_name: "hello"
},
header: {
"content-type": "application/json"
},
success(res) {
console.log(`request调用成功 ${res}`);
},
fail(res) {
console.log(`request调用失败`);
}
});
if (someReason) {
task.abort();
}
Bug & Tip
- header不支持设置referer