The network request library, based on fetch encapsulation, combines the features of fetch and axios to provide developers with a unified api call method, simplifying usage, and providing common functions such as caching, timeout, character encoding processing, and error handling.
Supported features
url parameter is automatically serialized
post data submission method is simplified
response return processing simplification
api timeout support
api request cache support
support for processing gbk
request and response interceptor support like axios
extend options Initialize default parameters, support all of the above
Parameter
Description
Type
Optional Value
Default
method
request method
string
get , post , put …
get
params
url request parameters
object
–
–
data
Submitted data
any
–
–
…
{
// 'method' is the request method to be used when making the request
method: 'get', // default
// 'params' are the URL parameters to be sent with request
// Must be a plain object or a URLSearchParams object
params: { id: 1 },
// 'paramSerializer' is a function in charge of serializing 'params'. ( be aware of 'params' was merged by extends's 'params' and request's 'params' and URLSearchParams will be transform to plain object. )
paramsSerializer: function (params) {
return Qs.stringify(params, { arrayFormat: 'brackets' })
},
// 'data' 作为请求主体被发送的数据
// 适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
// 必须是以下类型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 浏览器专属:FormData, File, Blob
// - Node 专属: Stream
// 'data' is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
// Must be of one of the following types:
// 1. string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// 2. Browser only: FormData, File, Blob
// 3. Node only: Stream
data: { name: 'Mike' },
// 'headers' are custom headers to be sent
headers: { 'Content-Type': 'multipart/form-data' },
// 'timeout' specifies the number of milliseconds before the request times out.
// If the request takes longer than 'timeout', request will be aborted and throw RequestError.
timeout: 1000,
// ’prefix‘ used to set URL's prefix
// ( e.g. request('/user/save', { prefix: '/api/v1' }) => request('/api/v1/user/save') )
prefix: '',
// ’suffix‘ used to set URL's suffix
// ( e.g. request('/api/v1/user/save', { suffix: '.json'}) => request('/api/v1/user/save.json') )
suffix: '',
// 'credentials' indicates whether the user agent should send cookies from the other domain in the case of cross-origin requests.
// omit: Never send or receive cookies.
// same-origin: Send user credentials (cookies, basic http auth, etc..) if the URL is on the same origin as the calling script. This is the default value.
// include: Always send user credentials (cookies, basic http auth, etc..), even for cross-origin calls.
credentials: 'same-origin', // default
// ’useCache‘ The GET request would be cache in ttl milliseconds when 'useCache' is true.
// The cache key would be 'url + params + method'.
useCache: false, // default
// 'ttl' cache duration(milliseconds),0 is infinity
ttl: 60000,
// 'maxCache' are the max number of requests to be cached, 0 means infinity.
maxCache: 0,
// According to http protocal, request of GET used to get data from server, it's necessary to cache response data when server data update not frequently. We provide 'validateCache'
// for some cases that need to cache data with other method reqeust.
validateCache: (url, options) => { return options.method.toLowerCase() === 'get' },
// 'requestType' umi-request will add headers and body according to the 'requestType' when the type of data is object or array.
// 1. requestType === 'json' :(default )
// options.headers = {
// Accept: 'application/json',
// 'Content-Type': 'application/json;charset=UTF-8',
// ...options.headers,
// }
// options.body = JSON.stringify(data)
//
// 2. requestType === 'form':
// options.headers = {
// Accept: 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
// ...options.headers,
// };
// options.body = query-string.stringify(data);
//
// 3. other requestType
// options.headers = {
// Accept: 'application/json',
// ...options.headers,
// };
// options.body = data;
requestType: 'json', // default
// 'parseResponse' whether processing response
parseResponse: true, // default
// 'charset' This parameter can be used when the server returns gbk to avoid garbled characters.(parseResponse should set to true)
charset: 'gbk',
// 'responseType': how to processing response.(parseResponse should be true)
// The default value is 'json', would processing response by Response.text().then( d => JSON.parse(d) )
// Other responseType (text, blob, arrayBuffer, formData), would processing response by Response[responseType]()
responseType: 'json', // default
// 'throwErrIfParseFail': whether throw error or not when JSON parse data fail and responseType is 'json'.
throwErrIfParseFail: false, // default
// 'getResponse': if you need the origin Response, set true and will return { data, response }.
getResponse: false,// default
// 'errorHandler' error handle entry.
errorHandler: function(error) { /* 异常处理 */ },
// 'cancelToken' the token of cancel request.
cancelToken: null,
}
Extend Options
Sometimes we need to update options after extend a request instance, umi-request provide extendOptions for users to update options:
The response for a request contains the following information.
{
// 'data' is the response that was provided by the server
data: {},
// 'status' is the HTTP status code from the server response
status: 200,
// 'statusText' is the HTTP status message from the server response
statusText: 'OK',
// 'headers' the headers that the server responded with
// All header names are lower cased
headers: {},
}
When options.getResponse === false, the response schema would be ‘data’
You can get Response from error object in errorHandler or request.catch.
Error handling
import request, { extend } from 'umi-request';
const errorHandler = function(error) {
const codeMap = {
'021': 'An error has occurred',
'022': 'It’s a big mistake,',
// ....
};
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.status);
console.log(error.response.headers);
console.log(error.data);
console.log(error.request);
console.log(codeMap[error.data.status]);
} else {
// The request was made but no response was received or error occurs when setting up the request.
console.log(error.message);
}
throw error; // If throw. The error will continue to be thrown.
// return {some: 'data'}; If return, return the value as a return. If you don't write it is equivalent to return undefined, you can judge whether the response has a value when processing the result.
// return {some: 'data'};
};
// 1. Unified processing
const extendRequest = extend({ errorHandler });
// 2. Separate special treatment
// If unified processing is configured, but an api needs special handling. When requested, the errorHandler is passed as a parameter.
request('/api/v1/xxx', { errorHandler });
// 3. not configure errorHandler, the response will be directly treated as promise, and it will be caught.
request('/api/v1/xxx')
.then(function(response) {
console.log(response);
})
.catch(function(error) {
return errorHandler(error);
});
Middleware
Expressive HTTP middleware framework for node.js. For development to enhance before and after request. Support create instance, global, core middlewares.
Instance Middleware (default) request.use(fn) Different instances’s instance middleware are independence.
Global Middleware request.use(fn, { global: true }) Different instances share global middlewares.
Core Middleware request.use(fn, { core: true }) Used to expand request core.
request.use(fn[, options])
params
fn params
ctx(Object):context, content request and response
next(Function):function to call the next middleware
options params
global(boolean): whether global, higher priority than core
Base on AbortController that allows you to abort one or more Web requests as and when desired.
// polyfill abort controller if needed
import 'yet-another-abortcontroller-polyfill'
import Request from 'umi-request';
const controller = new AbortController(); // create a controller
const { signal } = controller; // grab a reference to its associated AbortSignal object using the AbortController.signal property
signal.addEventListener('abort', () => {
console.log('aborted!');
});
Request('/api/response_after_1_sec', {
signal, // pass in the AbortSignal as an option inside the request's options object (see {signal}, below). This associates the signal and controller with the fetch request and allows us to abort it by calling AbortController.abort(),
});
// 取消请求
setTimeout(() => {
controller.abort(); // Aborts a DOM request before it has completed. This is able to abort fetch requests, consumption of any response Body, and streams.
}, 100);
Use Cancel Token
Cancel Token still work, but we don’t recommend using them in the new code.
You can cancel a request using a cancel token.
import Request from 'umi-request';
const CancelToken = Request.CancelToken;
const { token, cancel } = CancelToken.source();
Request.get('/api/cancel', {
cancelToken: token,
}).catch(function(thrown) {
if (Request.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
Request.post(
'/api/cancel',
{
name: 'hello world',
},
{
cancelToken: token,
}
);
// cancel request (the message parameter is optional)
cancel('Operation canceled by the user.');
You can also create a cancel token by passing an executor function to the CancelToken constructor:
import Request from 'umi-request';
const CancelToken = Request.CancelToken;
let cancel;
Request.get('/api/cancel', {
cancelToken: new CancelToken(function executor(c) {
cancel = c;
}),
});
// cancel request
cancel();
Use FormData() contructor,the browser will add request header "Content-Type: multipart/form-data" automatically, developer don’t need to add request header Content-Type
The Access-Control-Expose-Headers response header indicates which headers can be exposed as part of the response by listing their names.Access-Control-Expose-Headers
Development and debugging
npm install
npm run dev
npm link
Then go to the project you are testing to execute npm link umi-request
English | 简体中文
umi-request
The network request library, based on fetch encapsulation, combines the features of fetch and axios to provide developers with a unified api call method, simplifying usage, and providing common functions such as caching, timeout, character encoding processing, and error handling.
Supported features
umi-request vs fetch vs axios
For more discussion, refer to Traditional Ajax is dead, Fetch eternal life If you have good suggestions and needs, please mention issue
TODO Welcome pr
Installation
Example
Performing a
GETrequestPerforming a
POSTrequestumi-request API
Requests can be made by passing relevant options to
umi-requestumi-request(url[, options])
Request method aliases
For convenience umi-request have been provided for all supported methods.
request.get(url[, options])
request.post(url[, options])
request.delete(url[, options])
request.put(url[, options])
request.patch(url[, options])
request.head(url[, options])
request.options(url[, options])
Creating an instance
You can use
extend({[options]})to create a new instance of umi-request.extend([options])
Create an instance of umi-request in NodeJS enviroment
The available instance methods are list below. The specified options will be merge with the instance options.
request.get(url[, options])
request.post(url[, options])
request.delete(url[, options])
request.put(url[, options])
request.patch(url[, options])
request.head(url[, options])
request.options(url[, options])
More umi-request cases can see antd-pro
request options
timeoutfirstThe other parameters of fetch are valid. See fetch documentation
extend options Initialize default parameters, support all of the above
Extend Options
Sometimes we need to update options after extend a request instance, umi-request provide extendOptions for users to update options:
Response Schema
The response for a request contains the following information.
When options.getResponse === false, the response schema would be ‘data’
When options.getResponse === true ,the response schema would be { data, response }
You can get Response from
errorobject in errorHandler or request.catch.Error handling
Middleware
Expressive HTTP middleware framework for node.js. For development to enhance before and after request. Support create instance, global, core middlewares.
Instance Middleware (default) request.use(fn) Different instances’s instance middleware are independence. Global Middleware request.use(fn, { global: true }) Different instances share global middlewares. Core Middleware request.use(fn, { core: true }) Used to expand request core.
request.use(fn[, options])
params
fn params
options params
example
order of middlewares be called:
order of middlewares be called:
Interceptor
You can intercept requests or responses before they are handled by then or catch.
Cancel request
Use AbortController
Base on AbortController that allows you to abort one or more Web requests as and when desired.
Use Cancel Token
Cases
How to get Response Headers
Use Headers.get() (more detail see MDN 文档)
If want to get a custem header, you need to set Access-Control-Expose-Headers on server.
File upload
Use FormData() contructor,the browser will add request header
"Content-Type: multipart/form-data"automatically, developer don’t need to add request header Content-TypeThe Access-Control-Expose-Headers response header indicates which headers can be exposed as part of the response by listing their names.Access-Control-Expose-Headers
Development and debugging
Questions & Suggestions
Please open an issue here.
Code Contributors
LICENSE
MIT