README.md

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.

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 requestmethod: 'get',// default// 'params' are the URL parameters to be sent with request// Must be a plain object or a URLSearchParams objectparams: {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){returnQs.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: Streamdata: {name: 'Mike'},// 'headers' are custom headers to be sentheaders: {'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 infinityttl: 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)=>{returnoptions.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 responseparseResponse: 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:

Response Schema

The response for a request contains the following information.

{// 'data' is the response that was provided by the serverdata: {},// 'status' is the HTTP status code from the server responsestatus: 200,// 'statusText' is the HTTP status message from the server responsestatusText: 'OK',// 'headers' the headers that the server responded with// All header names are lower casedheaders: {},}

When options.getResponse === false, the response schema would be 'data'

You can get Response from error object in errorHandler or request.catch.

Error handling

importrequest,{extend}from'umi-request';consterrorHandler=function(error){constcodeMap={'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 2xxconsole.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);}throwerror;// 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 processingconstextendRequest=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){returnerrorHandler(error);});

Middleware

Expressive HTTP middleware framework for node.js. For development to enhance before and after request. Support create instance, global, core middlewares.

Cancel request

Use AbortController

Base on AbortController that allows you to abort one or more Web requests as and when desired.

importRequest,{AbortController}from'umi-request';constcontroller=newAbortController();// create a controllerconst{ signal }=controller;// grab a reference to its associated AbortSignal object using the AbortController.signal propertysignal.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.