Encapsulate XHR request, export simple GET, POST, PUT,delete, upload file request methods
- Installation, NPM/YARN installation
npm install xhr-fetch-lib
yarn add xhr-fetch-lib
Copy the code
- Use the sample
import fetch, { get, post, put, del, upload } from 'xhr-fetch-lib';
// Call get post put del
get(apiUrl).then((res) = > {
responseHandler(res);
});
// Use the fetch setting to return a bloB for the download
fetch({
url,
method,
data,
xhrSetting: { responseType: 'blob' },
responseParser: (xhr) = > xhr.response,
}).then((blob) = > {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
a.click();
});
// File upload
const file = e.target.files[0];
upload(api, { key: 'value' }, file, null.(e) = > console.log(e.percent));
Copy the code
- Typescript type definitions
exportdeclare type Options = { method? :'get' | 'post' | 'put' | 'delete' | 'head'; url: string; data? : Record<string, unknown> | string; headers? : Record<string, string>; withCredentials? : boolean; responseParser? :(xhr: XMLHttpRequest) = >unknown; xhrSetting? : XHRSetting; }; declare type XHRSetting = { responseType? : XMLHttpRequestResponseType; timeout? : number; [p: string]: unknown; }; declareconst fetch: ({ method, url, data, headers, withCredentials, responseParser, xhrSetting? : XHRSetting; }: Options) = > Promise<unknown>;
export default fetch;
export declare const get: (
url: string,
data: Record<string, unknown> | string | null, headers? : Record<string, string>) = > Promise<unknown>;
export declare const post: (
url: string,
data: Record<string, unknown> | string | null, headers? : Record<string, string>) = > Promise<unknown>;
export declare const put: (
url: string,
data: Record<string, unknown> | string | null, headers? : Record<string, string>) = > Promise<unknown>;
export declare const del: (
url: string,
data: Record<string, unknown> | string | null, headers? : Record<string, string>) = > Promise<unknown>;
export default function upload(
url: string,
data: Record<string, unknown> | null, file: File | Blob, headers? : Record<string, string> |null, onProgress? : ( e: ProgressEvent & { percent: number; }) = >void
) :Promise<XMLHttpRequest>;
Copy the code
- The return value
The default is jSON-bigInt parse’s object, the same value returned by json.parse.
import JSONbig from 'json-bigint';
const JSONBig = JSONbig({ storeAsString: true });
function parseResponse(xhr: XMLHttpRequest) :unknown {
let result;
try {
result = JSONBig.parse(xhr.responseText);
} catch (e) {
result = xhr.responseText;
}
return result;
}
Copy the code
-
For GET requests, data uses object key-value pairs, which are converted to the key=value&key1=value1 format by default. Key =value string format can also be passed in
-
Parse responseText (json-bigint.parse responseText
-
Fetch can customize XMLHttpRequest properties, such as responseType,timeout, and so on