@neosjs/request
v2.1.0
Published
NeosJS Request
Downloads
37
Readme
@neosjs/request
发起 HTTP、HTTPS 网络请求。(基于axios进行的二次封装)
使用方法
request 用法
基础使用
import request from '@neosjs/request'
// 示例1
request({
url:'http://api.com',
params:{
user:1
}
}).then(res => {
console.log(res)
}).catch(err => {
console.log(res)
})
// 示例2
request('http://api.com',{
params:{
user:1
}
}).then(res => {
console.log(res)
}).catch(err => {
console.log(res)
})
// 示例3
request({
method:'POST',
url:'http://api.com',
params:{
user:1
},
// 发起请求之前的回调函数
before: () => {
console.log('before')
},
// 成功返回的回调函数
success: (res) => {
console.log(res)
},
// 接口调用失败的回调函数
fail: (err) => {
console.log(err)
},
// 接口调用结束的回调函数(调用成功、失败都会执行)
complete: () => {
console.log('complete')
}
})
async/await 用法
import request from '@neosjs/request'
const res = await request({
url:'https://api.com',
params:{
id:1
}
})
requestAll
import { requestAll } from '@neosjs/request'
const requestA = await request({}) // 请求1
const requestB = await request({}) // 请求2
const res = requestAll([requestA,requestB])
console.log(res)
requestInstance
import { requestInstance } from '@neosjs/request'
const data = await requestInstance.get('https://api.com',{
// ....
})
const data = await requestInstance.post('https://api.com',{
// ....
})
const data = await requestInstance({url:'https://api.com'})
requestInstance
的使用方法,同axios
一致。 请注意: 某些参数可能对requestInstance
无效。
参数说明
| 参数 | 说明 | 类型 | 可选值 | 默认值 | | --------------- | ------------------------ | -------- | -------------------------------------- | ----- | | url | 请求的api地址 | String | - | - | | method | 请求类型 | String | POST、GET、DELETE、HEAD、OPTIONS、PUT、PATCH | GET | | dataType | 返回数据类型 | String | - | json | | timeout | 超时时间 | Number | - | 10000 | | withCredentials | 是否传递cookie | Boolean | - | false | | params | 请求的参数 | Object | - | - | | retry | 重试次数 | Number | - | 1 | | retryDelay | 重试间隔时间(ms) | Number | - | 2000 | | cache | 是否开启缓存 | Boolean | - | true | | cacheMaxAge | 缓存时间(ms) | Number | - | 60000 | | forceUpdate | 是否强制更新缓存 | Boolean | - | false | | cancelRequest | 是否取消重复请求 | Boolean | - | false | | headers | 设置请求的 header | Object | - | {'Content-Type': 'application/json'} | | before | 发起请求之前的回调函数 | Function | - | null | | after | 请求完成后的回调函数 | Function | - | null | | success | 成功返回的回调函数 | Function | - | null | | fail | 接口调用失败的回调函数 | Function | - | null | | complete | 接口调用结束的回调函数(调用成功、失败都会执行) | Function | - | null |