HiRequest 【hi-got】
为了方便以及统一大家对于数据请求的方式,HiUI 特封装请求工具 HiRequest
快速使用
import HiRequest from '@hi-ui/hiui/es/hi-request'
HiRequest.get('/user?ID=12345').then((response) => {
console.log(response)
})
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.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: '下载文件名',
params: {
id: 1
},
withCredentials: true,
headers: {
token: 'token'
},
onDownloadProgress: (progressEvent) => {
},
downloadSuccess: (res) => {
},
downloadFail: (res) => {
}
})
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... }
)
HiRequest API
HiRequest(config)
HiRequest({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
})
HiRequest({
method: 'get',
url: 'http://bit.ly/2mTM3nY',
responseType: 'stream'
}).then(function (response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
})
HiRequest(url[, config])
HiRequest('/user/12345')
为了方便起见,为所有支持的请求方法提供了别名。
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.getCookiesParam(url[, data[, config]])
HiRequest.upload(url[, data[, config]])
HiRequest.jsonp(url[, data[, config]])
Request Config
HiRequest.getCookiesParam(key)
{
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'
},
filename: '未命名',
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) {
})
}
Response Schema
The response for a request contains the following information.
{
data: {},
status: 200,
statusText: 'OK',
headers: {},
config: {},
request: {}
}
When using then
, you will receive the response as follows:
HiRequest.get('/user/12345').then(function (response) {
console.log(response.data)
console.log(response.status)
console.log(response.statusText)
console.log(response.headers)
console.log(response.config)
})
Handling 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)
})
Using the validateStatus
config option, you can define HTTP code(s) that should throw an error.
HiRequest.get('/user/12345', {
validateStatus: function (status) {
return status < 500
}
})
Using toJSON
you get an object with more information about the HTTP error.
HiRequest.get('/user/12345').catch(function (error) {
console.log(error.toJSON())
})
Cancellation
You can cancel a request using a cancel token.
The HiRequest cancel token API is based on the withdrawn cancelable promises proposal.
You can create a cancel token using the CancelToken.source
factory as shown below:
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.')
You can also create a cancel token by passing an executor function to the CancelToken
constructor:
const CancelToken = HiRequest.CancelToken
let cancel
HiRequest.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
cancel = c
})
})
cancel()
Note that URLSearchParams
is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).
Alternatively, you can encode data using the qs
library:
const qs = require('qs')
HiRequest.post('/foo', qs.stringify({ bar: 123 }))
Or in another way (ES6),
import qs from 'qs'
const data = { bar: 123 }
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: qs.stringify(data),
url
}
HiRequest(options)
Node.js
In node.js, you can use the querystring
module as follows:
const querystring = require('querystring')
HiRequest.post('http://something.com/', querystring.stringify({ foo: 'bar' }))