Gathering detailed insights and metrics for umi-request
Gathering detailed insights and metrics for umi-request
Gathering detailed insights and metrics for umi-request
Gathering detailed insights and metrics for umi-request
npm install umi-request
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
2,206 Stars
132 Commits
335 Forks
50 Watching
3 Branches
32 Contributors
Updated on 19 Nov 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
7.1%
4,555
Compared to previous day
Last week
5%
23,997
Compared to previous week
Last month
20%
95,053
Compared to previous month
Last year
-30.9%
1,235,070
Compared to previous year
English | 简体中文
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.
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
npm install --save umi-request
Performing a GET
request
1import request from 'umi-request'; 2 3request 4 .get('/api/v1/xxx?id=1') 5 .then(function(response) { 6 console.log(response); 7 }) 8 .catch(function(error) { 9 console.log(error); 10 }); 11 12// use options.params 13request 14 .get('/api/v1/xxx', { 15 params: { 16 id: 1, 17 }, 18 }) 19 .then(function(response) { 20 console.log(response); 21 }) 22 .catch(function(error) { 23 console.log(error); 24 });
Performing a POST
request
1request 2 .post('/api/v1/user', { 3 data: { 4 name: 'Mike', 5 }, 6 }) 7 .then(function(response) { 8 console.log(response); 9 }) 10 .catch(function(error) { 11 console.log(error); 12 });
Requests can be made by passing relevant options to umi-request
umi-request(url[, options])
1import request from 'umi-request'; 2 3request('/api/v1/xxx', { 4 method: 'get', 5 params: { id: 1 }, 6}) 7 .then(function(response) { 8 console.log(response); 9 }) 10 .catch(function(error) { 11 console.log(error); 12 }); 13 14request('/api/v1/user', { 15 method: 'post', 16 data: { 17 name: 'Mike', 18 }, 19}) 20 .then(function(response) { 21 console.log(response); 22 }) 23 .catch(function(error) { 24 console.log(error); 25 });
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])
You can use extend({[options]})
to create a new instance of umi-request.
extend([options])
1import { extend } from 'umi-request'; 2 3const request = extend({ 4 prefix: '/api/v1', 5 timeout: 1000, 6 headers: { 7 'Content-Type': 'multipart/form-data', 8 }, 9}); 10 11request 12 .get('/user') 13 .then(function(response) { 14 console.log(response); 15 }) 16 .catch(function(error) { 17 console.log(error); 18 });
Create an instance of umi-request in NodeJS enviroment
1const umi = require('umi-request'); 2const extendRequest = umi.extend({ timeout: 10000 }); 3 4extendRequest('/api/user') 5 .then(res => { 6 console.log(res); 7 }) 8 .catch(err => { 9 console.log(err); 10 });
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
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
Parameter | Description | Type | Optional Value | Default |
---|---|---|---|---|
method | request method | string | get , post , put ... | get |
params | url request parameters | object | -- | -- |
data | Submitted data | any | -- | -- |
... |
1{ 2 // 'method' is the request method to be used when making the request 3 method: 'get', // default 4 5 // 'params' are the URL parameters to be sent with request 6 // Must be a plain object or a URLSearchParams object 7 params: { id: 1 }, 8 9 // '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. ) 10 paramsSerializer: function (params) { 11 return Qs.stringify(params, { arrayFormat: 'brackets' }) 12 }, 13 14 // 'data' 作为请求主体被发送的数据 15 // 适用于这些请求方法 'PUT', 'POST', 和 'PATCH' 16 // 必须是以下类型之一: 17 // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams 18 // - 浏览器专属:FormData, File, Blob 19 // - Node 专属: Stream 20 21 // 'data' is the data to be sent as the request body 22 // Only applicable for request methods 'PUT', 'POST', and 'PATCH' 23 // Must be of one of the following types: 24 // 1. string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams 25 // 2. Browser only: FormData, File, Blob 26 // 3. Node only: Stream 27 data: { name: 'Mike' }, 28 29 // 'headers' are custom headers to be sent 30 headers: { 'Content-Type': 'multipart/form-data' }, 31 32 // 'timeout' specifies the number of milliseconds before the request times out. 33 // If the request takes longer than 'timeout', request will be aborted and throw RequestError. 34 timeout: 1000, 35 36 // ’prefix‘ used to set URL's prefix 37 // ( e.g. request('/user/save', { prefix: '/api/v1' }) => request('/api/v1/user/save') ) 38 prefix: '', 39 40 // ’suffix‘ used to set URL's suffix 41 // ( e.g. request('/api/v1/user/save', { suffix: '.json'}) => request('/api/v1/user/save.json') ) 42 suffix: '', 43 44 // 'credentials' indicates whether the user agent should send cookies from the other domain in the case of cross-origin requests. 45 // omit: Never send or receive cookies. 46 // 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. 47 // include: Always send user credentials (cookies, basic http auth, etc..), even for cross-origin calls. 48 credentials: 'same-origin', // default 49 50 // ’useCache‘ The GET request would be cache in ttl milliseconds when 'useCache' is true. 51 // The cache key would be 'url + params + method'. 52 useCache: false, // default 53 54 // 'ttl' cache duration(milliseconds),0 is infinity 55 ttl: 60000, 56 57 // 'maxCache' are the max number of requests to be cached, 0 means infinity. 58 maxCache: 0, 59 60 // 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' 61 // for some cases that need to cache data with other method reqeust. 62 validateCache: (url, options) => { return options.method.toLowerCase() === 'get' }, 63 64 65 // 'requestType' umi-request will add headers and body according to the 'requestType' when the type of data is object or array. 66 // 1. requestType === 'json' :(default ) 67 // options.headers = { 68 // Accept: 'application/json', 69 // 'Content-Type': 'application/json;charset=UTF-8', 70 // ...options.headers, 71 // } 72 // options.body = JSON.stringify(data) 73 // 74 // 2. requestType === 'form': 75 // options.headers = { 76 // Accept: 'application/json', 77 // 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', 78 // ...options.headers, 79 // }; 80 // options.body = query-string.stringify(data); 81 // 82 // 3. other requestType 83 // options.headers = { 84 // Accept: 'application/json', 85 // ...options.headers, 86 // }; 87 // options.body = data; 88 requestType: 'json', // default 89 90 // 'parseResponse' whether processing response 91 parseResponse: true, // default 92 93 // 'charset' This parameter can be used when the server returns gbk to avoid garbled characters.(parseResponse should set to true) 94 charset: 'gbk', 95 96 // 'responseType': how to processing response.(parseResponse should be true) 97 // The default value is 'json', would processing response by Response.text().then( d => JSON.parse(d) ) 98 // Other responseType (text, blob, arrayBuffer, formData), would processing response by Response[responseType]() 99 responseType: 'json', // default 100 101 // 'throwErrIfParseFail': whether throw error or not when JSON parse data fail and responseType is 'json'. 102 throwErrIfParseFail: false, // default 103 104 // 'getResponse': if you need the origin Response, set true and will return { data, response }. 105 getResponse: false,// default 106 107 // 'errorHandler' error handle entry. 108 errorHandler: function(error) { /* 异常处理 */ }, 109 110 // 'cancelToken' the token of cancel request. 111 cancelToken: null, 112}
Sometimes we need to update options after extend a request instance, umi-request provide extendOptions for users to update options:
1const request = extend({ timeout: 1000, params: { a: '1' } }); 2// default options is: { timeout: 1000, params: { a: '1' }} 3 4request.extendOptions({ timeout: 3000, params: { b: '2' } }); 5// after extendOptions: { timeout: 3000, params: { a: '1', b: '2' }}
The response for a request contains the following information.
1{ 2 // 'data' is the response that was provided by the server 3 data: {}, 4 5 // 'status' is the HTTP status code from the server response 6 status: 200, 7 8 // 'statusText' is the HTTP status message from the server response 9 statusText: 'OK', 10 11 // 'headers' the headers that the server responded with 12 // All header names are lower cased 13 headers: {}, 14}
When options.getResponse === false, the response schema would be 'data'
1request.get('/api/v1/xxx', { getResponse: false }).then(function(data) { 2 console.log(data); 3});
When options.getResponse === true ,the response schema would be { data, response }
1request.get('/api/v1/xxx', { getResponse: true }).then(function({ data, response }) { 2 console.log(data); 3 console.log(response.status); 4 console.log(response.statusText); 5 console.log(response.headers); 6});
You can get Response from error
object in errorHandler or request.catch.
1import request, { extend } from 'umi-request'; 2 3const errorHandler = function(error) { 4 const codeMap = { 5 '021': 'An error has occurred', 6 '022': 'It’s a big mistake,', 7 // .... 8 }; 9 if (error.response) { 10 // The request was made and the server responded with a status code 11 // that falls out of the range of 2xx 12 console.log(error.response.status); 13 console.log(error.response.headers); 14 console.log(error.data); 15 console.log(error.request); 16 console.log(codeMap[error.data.status]); 17 } else { 18 // The request was made but no response was received or error occurs when setting up the request. 19 console.log(error.message); 20 } 21 22 throw error; // If throw. The error will continue to be thrown. 23 24 // 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. 25 // return {some: 'data'}; 26}; 27 28// 1. Unified processing 29const extendRequest = extend({ errorHandler }); 30 31// 2. Separate special treatment 32// If unified processing is configured, but an api needs special handling. When requested, the errorHandler is passed as a parameter. 33request('/api/v1/xxx', { errorHandler }); 34 35// 3. not configure errorHandler, the response will be directly treated as promise, and it will be caught. 36request('/api/v1/xxx') 37 .then(function(response) { 38 console.log(response); 39 }) 40 .catch(function(error) { 41 return errorHandler(error); 42 });
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])
fn params
options params
1import request, { extend } from 'umi-request'; 2request.use(async (ctx, next) => { 3 console.log('a1'); 4 await next(); 5 console.log('a2'); 6}); 7request.use(async (ctx, next) => { 8 console.log('b1'); 9 await next(); 10 console.log('b2'); 11}); 12 13const data = await request('/api/v1/a');
order of middlewares be called:
1a1 -> b1 -> response -> b2 -> a2
1request.use(async (ctx, next) => { 2 console.log('instanceA1'); 3 await next(); 4 console.log('instanceA2'); 5}); 6request.use(async (ctx, next) => { 7 console.log('instanceB1'); 8 await next(); 9 console.log('instanceB2'); 10}); 11request.use( 12 async (ctx, next) => { 13 console.log('globalA1'); 14 await next(); 15 console.log('globalA2'); 16 }, 17 { global: true } 18); 19request.use( 20 async (ctx, next) => { 21 console.log('coreA1'); 22 await next(); 23 console.log('coreA2'); 24 }, 25 { core: true } 26);
order of middlewares be called:
1instanceA1 -> instanceB1 -> globalA1 -> coreA1 -> coreA2 -> globalA2 -> instanceB2 -> instanceA2
1request.use(async (ctx, next) => { 2 const { req } = ctx; 3 const { url, options } = req; 4 5 if (url.indexOf('/api') !== 0) { 6 ctx.req.url = `/api/v1/${url}`; 7 } 8 ctx.req.options = { 9 ...options, 10 foo: 'foo', 11 }; 12 13 await next(); 14 15 const { res } = ctx; 16 const { success = false } = res; 17 if (!success) { 18 // ... 19 } 20});
1request.use( 2 async (ctx, next) => { 3 const { req } = ctx; 4 const { url, options } = req; 5 const { __umiRequestCoreType__ = 'normal' } = options; 6 7 // __umiRequestCoreType__ use to identificat request core 8 // when value is 'normal' , use umi-request 's fetch request core 9 if (__umiRequestCoreType__ === 'normal') { 10 await next(); 11 return; 12 } 13 14 // when value is not normal, use your request func. 15 const response = getResponseByOtherWay(); 16 17 ctx.res = response; 18 19 await next(); 20 return; 21 }, 22 { core: true } 23); 24 25request('/api/v1/rpc', { 26 __umiRequestCoreType__: 'rpc', 27 parseResponse: false, 28}) 29 .then(function(response) { 30 console.log(response); 31 }) 32 .catch(function(error) { 33 console.log(error); 34 });
You can intercept requests or responses before they are handled by then or catch.
1// request interceptor, change url or options. 2request.interceptors.request.use((url, options) => { 3 return { 4 url: `${url}&interceptors=yes`, 5 options: { ...options, interceptors: true }, 6 }; 7}); 8 9// Same as the last one 10request.interceptors.request.use( 11 (url, options) => { 12 return { 13 url: `${url}&interceptors=yes`, 14 options: { ...options, interceptors: true }, 15 }; 16 }, 17 { global: true } 18); 19 20// response interceptor, chagne response 21request.interceptors.response.use((response, options) => { 22 response.headers.append('interceptors', 'yes yo'); 23 return response; 24}); 25 26// handling error in response interceptor 27request.interceptors.response.use(response => { 28 const codeMaps = { 29 502: '网关错误。', 30 503: '服务不可用,服务器暂时过载或维护。', 31 504: '网关超时。', 32 }; 33 message.error(codeMaps[response.status]); 34 return response; 35}); 36 37// clone response in response interceptor 38request.interceptors.response.use(async response => { 39 const data = await response.clone().json(); 40 if (data && data.NOT_LOGIN) { 41 location.href = '登录url'; 42 } 43 return response; 44});
1// Global interceptors are used `request` instance method directly 2request.interceptors.request.use( 3 (url, options) => { 4 return { 5 url: `${url}&interceptors=yes`, 6 options: { ...options, interceptors: true }, 7 }; 8 }, 9 { global: false } 10); // second paramet defaults { global: true } 11 12function createClient(baseUrl) { 13 const request = extend({ 14 prefix: baseUrl, 15 }); 16 return request; 17} 18 19const clientA = createClient('/api'); 20const clientB = createClient('/api'); 21// Independent instance Interceptor 22clientA.interceptors.request.use( 23 (url, options) => { 24 return { 25 url: `${url}&interceptors=clientA`, 26 options, 27 }; 28 }, 29 { global: false } 30); 31 32clientB.interceptors.request.use( 33 (url, options) => { 34 return { 35 url: `${url}&interceptors=clientB`, 36 options, 37 }; 38 }, 39 { global: false } 40);
Base on AbortController that allows you to abort one or more Web requests as and when desired.
1// polyfill abort controller if needed 2import 'yet-another-abortcontroller-polyfill' 3import Request from 'umi-request'; 4 5const controller = new AbortController(); // create a controller 6const { signal } = controller; // grab a reference to its associated AbortSignal object using the AbortController.signal property 7 8signal.addEventListener('abort', () => { 9 console.log('aborted!'); 10}); 11 12Request('/api/response_after_1_sec', { 13 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(), 14}); 15 16// 取消请求 17setTimeout(() => { 18 controller.abort(); // Aborts a DOM request before it has completed. This is able to abort fetch requests, consumption of any response Body, and streams. 19}, 100);
Cancel Token still work, but we don’t recommend using them in the new code.
1import Request from 'umi-request'; 2 3const CancelToken = Request.CancelToken; 4const { token, cancel } = CancelToken.source(); 5 6Request.get('/api/cancel', { 7 cancelToken: token, 8}).catch(function(thrown) { 9 if (Request.isCancel(thrown)) { 10 console.log('Request canceled', thrown.message); 11 } else { 12 // handle error 13 } 14}); 15 16Request.post( 17 '/api/cancel', 18 { 19 name: 'hello world', 20 }, 21 { 22 cancelToken: token, 23 } 24); 25 26// cancel request (the message parameter is optional) 27cancel('Operation canceled by the user.');
1import Request from 'umi-request'; 2 3const CancelToken = Request.CancelToken; 4let cancel; 5 6Request.get('/api/cancel', { 7 cancelToken: new CancelToken(function executor(c) { 8 cancel = c; 9 }), 10}); 11 12// cancel request 13cancel();
Use Headers.get() (more detail see MDN 文档)
1request('/api/v1/some/api', { getResponse: true }).then(({ data, response }) => { 2 response.headers.get('Content-Type'); 3});
If want to get a custem header, you need to set Access-Control-Expose-Headers on server.
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
1const formData = new FormData(); 2formData.append('file', file); 3request('/api/v1/some/api', { method: 'post', data: formData, requestType: 'form',});
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
Please open an issue here.
MIT
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
Found 10/30 approved changesets -- score normalized to 3
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
license file not detected
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More