@easytool/http
Enhance axios features.
Extension features
- cache
- contentType
- beforeRequest
- afterResponse
- proxyURL
- preventDuplicate
- onError
- prepareRequest
- abortAll
- helpers
Install
npm install --save @easytool/http
Usage
Example
import http from '@easytool/http';
http({
baseURL: 'http://api.xxx.com',
url: '/user/123',
params: {
id: 1
}
}).then((data) => {
}, (error) => {
});
defaults
defaults is used for setup global options.
import http, { Method, ContentType } from '@easytool/http';
http.defaults({
baseURL: 'http://api.xxx.com',
method: Method.POST,
contentType: ContentType.APPLICATION_X_WWW_FORM_URLENCODED
withCredentials: true,
cache: false,
proxyURL: __DEV__ && '/api',
isDev: __DEV__
});
instance
instance method is used for set instance options and it will inherit global options.
import http, { Method, ContentType } from '@easytool/http';
var instance = http.create({
baseURL: 'http://api.xxx.com',
method: Method.POST,
contentType: ContentType.MULTIPART_FORM_DATA
});
instance({
url: '/user/123'
});
var request = instance.prepareRequest({
url: '/user/123'
});
prepareRequest
prepareRequest is used for preproccess request options, it will not send request but still execute below method:
beforeRequest() > proxyURL() > requestInterceptor() > transformRequest() > paramsSerializer(), and return a preproccess object:
{
url,
method,
headers,
params,
data,
toURL()
}
Example
import { prepareRequest } from '@easytool/http';
var request = prepareRequest({
baseURL: 'http://api.xxx.com',
url: '/user/123',
params: {
id: 1
}
});
Use for open or download file URL.
var request = prepareRequest({
baseURL: 'http://file.xxx.com',
url: '/file',
params: {
id: 1
}
});
window.open(request.toURL());
<a href={request.toURL()} target="_blank" >Download</a>
Use jQuery ajax lib.
$.get({
url: request.toURL(),
type: request.method,
data: request.data
headers: request.headers
})
Use Antd Upload Component.
import { Upload } from 'antd';
import { prepareRequest, Method } from '@easytool/http';
var request = prepareRequest({
baseURL: 'http://file.xxx.com',
url: '/api/file/upload',
method: Method.POST,
contentType: null,
headers: {
token: 'xxxx-xxxx-xxxx',
...
},
params
});
<Upload name="file" action={request.toURL()} headers={request.headers} ></Upload>
Handle file stream
import http from '@easytool/http';
http({
baseURL: 'http://api.xxx.com',
url: '/assets/images/cat.png',
responseType: 'blob'
}).then((response) => {
var blob = response.data;
if ('msSaveOrOpenBlob' in window.navigator) {
window.navigator.msSaveOrOpenBlob(blob, 'screenshot.png');
} else {
var a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = 'screenshot.png';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
});
proxyURL
proxyURL will proxy the request to local server and add the config proxyURL to the top of url.
proxyURL is true.
import http from '@easytool/http';
var promise = http({
baseURL: 'http://api.xxx.com',
url: '/user/123',
proxyURL: true
});
proxyURL is String.
import http from '@easytool/http';
var promise = http({
baseURL: 'http://api.xxx.com',
url: '/user/123',
proxyURL: '/api'
});
proxyURL is Function.
import http from '@easytool/http';
var promise = http({
baseURL: 'http://api.xxx.com',
url: '/user/123',
proxyURL: (baseURL, options) => '/proxy'
});
Use internal Function 'proxyBaseURL' to proxy baseURL.
import http, { helpers } from '@easytool/http';
var promise = http({
baseURL: 'http://api.xxx.com',
url: '/user/123',
proxyURL: helpers.proxy.proxyBaseURL
});
Interceptors
defaultInterceptor
import http from '@easytool/http';
http.defaults({
requestInterceptor(config) {
config.headers.TOKEN = 'xxxxxx';
return config;
},
responseInterceptor(response) {
return response;
}
});
http.defaults({
requestInterceptor: [function(config) {
return config;
}, function(error) {
return Promise.reject(error);
}],
responseInterceptor: [function(response) {
return response;
}, function(error) {
return Promise.reject(error);
}]
});
customInterceptor
import http from '@easytool/http';
http.interceptors.request.use(function (config) {
return config;
}, function (error) {
return Promise.reject(error);
});
http.interceptors.response.use(function (response) {
return response;
}, function (error) {
return Promise.reject(error);
});
Asynchronize Interceptors
beforeRequest
import http from '@easytool/http';
http({
url: '/user/123',
beforeRequest(resolve, reject, options) {
setTimeout(() => {
resolve(options);
reject('some error message.');
}, 2000)
}
});
afterResponse
import http from '@easytool/http';
http({
url: '/user/123',
afterResponse(resolve, reject, response, options) {
var { data, status } = response;
switch (status) {
case 200:
resolve(data);
case 401:
reject(response);
setTimeout(() => {
location.href = `http://api.xxx.com/login?callback=${encodeURIComponent(location.href)}`;
}, 0);
break;
case 500:
reject(response);
break;
}
}
});
Transform
transformRequest
import http, { Method, ContentType, helpers } from '@easytool/http';
http({
baseURL: 'http://api.xxx.com',
url: '/user/123',
transformRequest(data, headers, options) {
if (headers['Content-Type'] === ContentType.APPLICATION_X_WWW_FORM_URLENCODED) {
return helpers.qs.stringify(data, {
arrayFormat: 'brackets',
allowDots: true
});
}
return data;
}
});
transformResponse
http({
baseURL: 'http://api.xxx.com',
url: '/user/123',
transformResponse: [function (data, headers, options) {
return data;
}]
});
paramsSerializer
Serialize parameters.
import http, { prepareRequest, Method, ContentType, helpers } from '@easytool/http';
http({
baseURL: 'http://api.xxx.com',
url: '/user/123',
paramsSerializer(params) {
return helpers.qs.stringify(params, {
arrayFormat: 'brackets',
allowDots: true
});
}
});
let request = prepareRequest({
baseURL: 'http://api.xxx.com',
url: '/user/123',
paramsSerializer(params) {
return helpers.qs.stringify(params, {
arrayFormat: 'brackets',
allowDots: true
});
}
});
default paramsSerializer handler
Set to false or rewrite it could change default behavior.
paramsSerializer(params) {
return helpers.qs.stringify(params, {
allowDots: true
});
}
Cancellation
abortAll
abort all request without create cancelToken.
import http from '@easytool/http';
http({
url: '/user/123',
});
http({
url: '/user/321',
});
http.abortAll('Operation all canceled.');
CancelToken
import http from '@easytool/http';
const CancelToken = http.CancelToken;
const source = CancelToken.source();
http({
url: '/user/123',
cancelToken: source.token
});
source.cancel('Operation canceled by the user.');
API
Extension features
http(options)
http.defaults(options)
http.create(options)
http.abortAll(message)
prepareRequest(options)
Method
ContentType
helpers.proxy
proxyBaseURL(baseURL)
helpers.qs
refer to https://www.npmjs.com/package/qs