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
- 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
- unified error handling
- middleware support
- cancel request support like axios
- make http request from node.js
umi-request vs fetch vs axios
Features
umi-request
fetch
axios
implementation
Browser native support
Browser native support
XMLHttpRequest
size
9k
4k (polyfill)
14k
query simplification
✅
❌
✅
post simplification
✅
❌
❌
timeout
✅
❌
✅
cache
✅
❌
❌
error Check
✅
❌
❌
error Handling
✅
❌
✅
interceptor
✅
❌
✅
prefix
✅
❌
❌
suffix
✅
❌
❌
processing gbk
✅
❌
❌
middleware
✅
❌
❌
cancel request
✅
❌
✅
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
- Test case coverage 85%+
- write a document
- CI integration
- release configuration
- typescript
Installation
npm install --save umi-request
Example
Performing a GET
request
import request from 'umi-request'; request .get('/api/v1/xxx?id=1') .then(function(response) { console.log(response); }) .catch(function(error) { console.log(error); }); // use options.params request .get('/api/v1/xxx', { params: { id: 1, }, }) .then(function(response) { console.log(response); }) .catch(function(error) { console.log(error); });
Performing a POST
request
request .post('/api/v1/user', { data: { name: 'Mike', }, }) .then(function(response) { console.log(response); }) .catch(function(error) { console.log(error); });
umi-request API
Requests can be made by passing relevant options to umi-request
umi-request(url[, options])
import request from 'umi-request'; request('/api/v1/xxx', { method: 'get', params: { id: 1 }, }) .then(function(response) { console.log(response); }) .catch(function(error) { console.log(error); }); request('/api/v1/user', { method: 'post', data: { name: 'Mike', }, }) .then(function(response) { console.log(response); }) .catch(function(error) { console.log(error); });
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])
import { extend } from 'umi-request'; const request = extend({ prefix: '/api/v1', timeout: 1000, headers: { 'Content-Type': 'multipart/form-data', }, }); request .get('/user') .then(function(response) { console.log(response); }) .catch(function(error) { console.log(error); });
Create an instance of umi-request in NodeJS enviroment
const umi = require('umi-request'); const extendRequest = umi.extend({ timeout: 10000 }); extendRequest('/api/user') .then(res => { console.log(res); }) .catch(err => { console.log(err); });
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
Parameter
Description
Type
Optional Value
Default
method
request method
string
get , post , put …
get
params
url request parameters
object or URLSearchParams
—
—
data
Submitted data
any
—
—
headers
fetch original parameters
object
—
{}
timeout
timeout, default millisecond, write with caution
number
—
timeoutMessage
customize timeout error message, please config timeout
first
string
—
—
prefix
prefix, generally used to override the uniform settings prefix
string
—
—
suffix
suffix, such as some scenes api need to be unified .json
string
—
credentials
fetch request with cookies
string
—
credentials: ‘same-origin’
useCache
Whether to use caching (only support browser environment)
boolean
—
false
validateCache
cache strategy function
(url, options) => boolean
—
only get request to cache
ttl
Cache duration, 0 is not expired
number
—
60000
maxCache
Maximum number of caches
number
—
0(Infinity)
requestType
post request data type
string
json , form
json
parseResponse
response processing simplification
boolean
—
true
charset
character set
string
utf8 , gbk
utf8
responseType
How to parse the returned data
string
json , text , blob , formData …
json , text
throwErrIfParseFail
throw error when JSON parse fail and responseType is ‘json’
boolean
—
false
getResponse
Whether to get the source response, the result will wrap a layer
boolean
—
fasle
errorHandler
exception handling, or override unified exception handling
function(error)
—
cancelToken
Token to cancel request
CancelToken.token
—
—
The other parameters of fetch are valid. See fetch documentation
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...