HiRequest 【hi-got】
为了方便以及统一大家对于数据请求的方式,HiUI 特封装请求工具 HiRequest
支持 AMD/CJS/ESM 模块引入
import HiRequest from 'hi-request';
const HiRequest = require('hi-request');
require(['hi-request'],function(){
...
})
<script src="https://xxx.com/hi-request.min.js"></script>
Get 请求
HiRequest.get('/user?ID=12345')
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
.then(function () {
})
HiRequest.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
.then(function () {
})
async function getUser() {
try {
const response = await HiRequest.get('/user?ID=12345')
console.log(response)
} catch (error) {
console.error(error)
}
}
POST 请求
HiRequest({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
})
HiRequest.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
执行多个并发请求
function getUserAccount() {
return HiRequest.get('/user/12345')
}
function getUserPermissions() {
return HiRequest.get('/user/12345/permissions')
}
HiRequest.all([getUserAccount(), getUserPermissions()]).then(
HiRequest.spread(function (acct, perms) {
})
)
Upload 上传文件 请求方法
HiRequest.upload(({
url: 'https://upload',
name: 'filename',
file: '',
params: {
id:1
},
withCredentials:true,
headers: {
token:'token'
},
onUploadProgress: (event) => {
}
}).then((res) => {
if (res.status === 200) {
} else {
onerror(res.response)
}
}).catch(error => {
onerror(error.response)
});
Download 下载文件 请求方法
HiRequest.download({
url: 'https://download',
filename: '下载文件名.txt',
fileType: '',
params: {
id: 1
},
withCredentials: true,
headers: {
token: 'token'
},
onDownloadProgress: (progressEvent) => {
},
downloadSuccess: (res) => {
},
downloadFail: (res) => {
}
})
HiRequest({
method: 'get',
url: 'http://bit.ly/2mTM3nY',
responseType: 'stream'
}).then(function (response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
})
HiRequest(url[, config],[host])
HiRequest('/user/12345', { method: 'get' }, 'api')
更多快捷使用方式
HiRequest(config)
HiRequest.get(url[, config])
HiRequest.delete(url[, config])
HiRequest.head(url[, config])
HiRequest.options(url[, config])
HiRequest.post(url[, data[, config]])
HiRequest.put(url[, data[, config]])
HiRequest.patch(url[, data[, config]])
HiRequest.upload(url[, data[, config]])
HiRequest.jsonp(url[, data[, config]])
JSONP 请求
HiRequest.jsonp('/users.jsonp')
.then(function (response) {
return response.json()
})
.then(function (json) {
console.log('parsed json', json)
})
.catch(function (ex) {
console.log('parsing failed', ex)
})
设置 JSONP 回调参数名称,默认为'callback'
HiRequest.jsonp('/users.jsonp', {
jsonpCallback: 'custom_callback'
})
.then(function (response) {
return response.json()
})
.then(function (json) {
console.log('parsed json', json)
})
.catch(function (ex) {
console.log('parsing failed', ex)
})
设置 JSONP 回调函数名称,默认为带 json_前缀的随机数
HiRequest.jsonp('/users.jsonp', {
jsonpCallbackFunction: 'function_name_of_jsonp_response'
})
.then(function (response) {
return response.json()
})
.then(function (json) {
console.log('parsed json', json)
})
.catch(function (ex) {
console.log('parsing failed', ex)
})
设置 JSONP 请求超时,默认为 5000ms
HiRequest.jsonp('/users.jsonp', {
timeout: 3000
})
.then(function (response) {
return response.json()
})
.then(function (json) {
console.log('parsed json', json)
})
.catch(function (ex) {
console.log('parsing failed', ex)
})
jsonpCallback
和之间的区别jsonCallbackFunction
这两个功能可以很容易地相互混淆,但是有一个明显的区别。
默认值为
jsonpCallback
,默认值为callback
。这是回调参数的名称jsonCallbackFunction
,默认值为null
。这是回调函数的名称。为了使其与众不同,它是一个jsonp_
前缀为的随机字符串jsonp_1497658186785_39551
。如果由服务器设置,则将其保留为空白;如果回调函数名称是固定的,则将其显式设置。
Case 1:
HiRequest.jsonp('/users.jsonp', {
jsonpCallback: 'cb'
})
请求网址将为/users.jsonp?cb=jsonp_1497658186785_39551
,并且服务器应使用以下函数进行响应:
jsonp_1497658186785_39551(
{ ...data here... }
)
Case 2:
HiRequest.jsonp('/users.jsonp', {
jsonpCallbackFunction: 'search_results'
})
请求网址将为/users.jsonp?callback=search_results
,并且服务器应始终使用名为的函数进行响应search_results
search_results(
{ ...data here... }
)
HiRequestAPI
{
url: '/user',
method: 'get',
type: 'basics',
file?: any,
name?: string,
beforeRequest: [function (config){
return config
}],
beforeResponse: [function (res){
return res
}],
errorResponse: [function (error){
console.log(error.response)
}],
errorRequest: [function (error){
console.log(error.request)
}],
errorCallback: function (error){
console.log(err,error.request || error.response)
},
baseURL: 'https://some-domain.com/api/',
transformRequest: [function (data, headers) {
return data;
}],
transformResponse: [function (data) {
return data;
}],
headers: {'X-Requested-With': 'XMLHttpRequest'},
params: {
ID: 12345
},
data: {
firstName: 'Fred'
},
data: 'Country=Brasil&City=Belo Horizonte',
timeout: 1000,
withCredentials: false,
adapter: function (config) {
},
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
responseType: 'json',
responseEncoding: 'utf8',
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
onUploadProgress: function (progressEvent) {
},
onDownloadProgress: function (progressEvent) {
},
maxContentLength: 2000,
validateStatus: function (status) {
return status >= 200 && status < 300;
},
maxRedirects: 5,
socketPath: null,
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
proxy: {
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
cancelToken: new CancelToken(function (cancel) {
})
}
Errors 异常处理
HiRequest.get('/user/12345').catch(function (error) {
if (error.response) {
console.log(error.response.data)
console.log(error.response.status)
console.log(error.response.headers)
} else if (error.request) {
console.log(error.request)
} else {
console.log('Error', error.message)
}
console.log(error.config)
})
使用' validateStatus '配置选项,您可以定义应该抛出错误的 HTTP 代码。
HiRequest.get('/user/12345', {
validateStatus: function (status) {
return status < 500
}
})
使用' toJSON '你得到一个对象更多的信息,关于 HTTP 错误。
HiRequest.get('/user/12345').catch(function (error) {
console.log(error.toJSON())
})
取消请求
cancelable promises proposal.
通过使用 CancelToken.source
生成一个标记,用作取消使用
const CancelToken = HiRequest.CancelToken
const source = CancelToken.source()
HiRequest.get('/user/12345', {
cancelToken: source.token
}).catch(function (thrown) {
if (HiRequest.isCancel(thrown)) {
console.log('Request canceled', thrown.message)
} else {
}
})
HiRequest.post('/user/12345', {
name: 'new name',
cancelToken: source.token
})
source.cancel('Operation canceled by the user.')
你也可以通过传递一个 executor
函数给 CancelToken
构造函数来创建一个取消令牌:
const CancelToken = HiRequest.CancelToken
let cancel
HiRequest.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
cancel = c
})
})
cancel()
使用建议
import HiRequest from '@hi-ui/hiui/es/hi-request'
const HttpClient = (url, options = {}, host = 'api') => {
const { headers, ...restOptions } = options
return HiRequest(
{
url,
headers: {
token: 'user.token',
...headers
},
beforeRequest: (config) => {
return config
},
beforeResponse: (res) => {
return res
},
errorResponse: (error) => {
console.log(error.response)
},
errorRequest: (error) => {
console.log(error.request)
},
errorCallback: (error) => {
console.log(err, error.request || error.response)
},
...restOptions
},
host
).then(
(response) => {
const res = response.data
if (res.code === 401) {
return
}
return res
},
(error) => {
throw error
}
)
}
export default HttpClient