Simple XHR request library, including get, POST, PUT,delete, upload file upload methods

1. Install the NPM/YARN installation

npm install xhr-fetch-lib
yarn add xhr-fetch-lib
Copy the code

2. Ts type definition

  • The fetch is exported by default
declare const fetch: ({ method, url, data, headers, withCredentials, responseParser, xhrSetting, }: Options) = > Promise<Record<string, unknown> | string>;

export declare type Options = {
    /** Request method */method? :'get' | 'post' | 'put' | 'delete' | 'head';
    /** Request url */
    url: string;
    /** Request data, for get requests, data with object will default to the key=value&key1=value1 format */data? : Record<string, unknown> | string;/** Request header */headers? : Record<string, string>;/** withCredentials set, default true */withCredentials? : boolean;/** Process the XHR response */responseParser? :(xhr: XMLHttpRequest) = > Record<string, unknown> | string;
    /** XHR Settings, e.g. responseType,timeout, etc. */xhrSetting? : XHRSetting; };export default fetch;

Copy the code
  • Get/post/put/delete method
declare type simpleRequest = (
/** Request url */
url: string,
/** Request data, for get requests, data with object will default to the key=value&key1=value1 format */
data: Record<string, unknown> | string,
/** Request header */
headers: Record<string, string>) = > Promise<Record<string, unknown> | string>;

export declare const get: simpleRequest;
export declare const post: simpleRequest;
export declare const put: simpleRequest;
export declare const del: simpleRequest;

Copy the code
  • Upload a file
/** * Upload file **@export
 * @param {string} Url API address *@param {(Record<string, unknown> | null)} The data data *@param {(File | Blob)} File File to be uploaded *@param {(Record<string, string> | null)} [headers] User-defined request header *@param {((e: ProgressEvent & { percent: number }) => void)} [onProgress] Upload progress callback *@return {*}  {Promise<XMLHttpRequest>}* /
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
  1. 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
  1. 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
  1. For GET requests, data with object is converted to the key=value&key1=value1 format by default

  2. Parse (xhr.responseText) jsonbig.parse (xhr.responseText)

  3. Fetch can customize XMLHttpRequest properties, such as responseType,timeout, and so on