Skip to content

xhr-Promisify

npm package

NPM versionNPM Downloadsjsdelivr

A lightweight Promise-based XHR library that wraps traditional XMLHttpRequest into a Promise interface to simplify asynchronous request development.


Installation

bash
npm add xhr-promisify
bash
pnpm add xhr-promisify
bash
yarn add xhr-promisify
html
<script src="https://cdn.jsdelivr.net/npm/xhr-promisify/dist/index.umd.min.js"></script>
<script>
  const { ajax } = XhrPromisify;
  // GET request
  ajax({
    url: 'https://api.example.com/data',
    method: 'GET'
  })
  .then(response => {
    console.log('Response data:', response);
  })
  .catch(error => {
    console.error('Request failed:', error);
  });
</script>

Quick Start

Basic Usage

javascript
import { ajax } from 'xhr-promisify';

// GET request
ajax({
  url: 'https://api.example.com/data',
  method: 'GET'
})
.then(response => {
  console.log('Response data:', response);
})
.catch(error => {
  console.error('Request failed:', error);
});

// Simplified syntax (async/await)
async function fetchData() {
  try {
    const response = await ajax({ url: '/api/data' });
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

API Documentation

ajax(options: AjaxRequestOptions | string): Promise<AjaxResponse>

Sends an HTTP request and returns a Promise.

Parameters

ParameterTypeRequiredDescription
urlstring✔️Request URL
methodstringRequest method (default: GET)
dataobjectRequest body (automatically serialized to JSON for POST/PUT methods)
timeoutnumberTimeout in milliseconds (default: 30000)
headersobjectCustom request headers
signalAbortSignalAbort the request via AbortController
queryobjectURL query parameters (auto-encoded)
authobjectBasic authentication ({ username, password })
withCredentialsbooleanWhether to include credentials (e.g., cookies)
responseTypestringResponse type (e.g., json, blob)
validateStatus(status: number) => booleanCustom logic for determining successful status codes

Return Value (AjaxResponse)

typescript
interface AjaxResponse {
  status: number;        // HTTP status code
  statusText: string;    // Status text
  headers: Record<string, string>; // Response headers
  data: any;             // Parsed response data
  request: XMLHttpRequest; // Native XHR object
}

Error Type (AjaxError)

All errors throw an AjaxError object with the following properties:

typescript
class AjaxError extends Error {
  code: string; // Error code (e.g., `ERR_NETWORK`)
  status?: number; // HTTP status code (if available)
  statusText?: string; // HTTP status text (if available)
  data?: any; // Response data (if available)
  request?: XMLHttpRequest; // Original request object (if available)
}

Exported Error Codes

Error CodeDescription
ABORT_ERRRequest was aborted
ERR_NETWORKNetwork error (e.g., DNS resolution failed)
ERR_HTTP_REQUEST_TIMEOUTRequest timed out
ERR_BAD_REQUESTHTTP 4xx status code error
ERR_BAD_RESPONSEHTTP 5xx status code error

Advanced Usage

Abort Requests

javascript
const controller = new AbortController();
const { signal } = controller;

ajax({
  url: '/api/long-polling',
  signal
}).then(...);

// Abort the request manually
controller.abort();

Custom Headers

javascript
ajax({
  url: '/api/protected',
  headers: {
    'Authorization': 'Bearer your_token'
  }
});

Handle Progress Events

javascript
ajax({
  url: '/api/upload',
  onUploadProgress: (event) => {
    console.log(`Upload progress: ${event.loaded}/${event.total}`);
  },
  onDownloadProgress: (event) => {
    console.log(`Download progress: ${event.loaded}/${event.total}`);
  }
});

Error Handling

All exceptions throw an AjaxError object with the following properties:

typescript
class AjaxError extends Error {
  code: string; // Error code (e.g., `ERR_NETWORK`)
  status?: number; // HTTP status code (if available)
  statusText?: string; // HTTP status text (if available)
  data?: any; // Response data (if available)
  request?: XMLHttpRequest; // Original request object (if available)
}

Error Types

Error CodeTypeDescription
ABORT_ERRAjaxErrorRequest was manually aborted
ERR_NETWORKAjaxErrorNetwork error (e.g., DNS resolution failure)
ERR_HTTP_REQUEST_TIMEOUTAjaxErrorRequest timeout
ERR_BAD_REQUESTAjaxErrorHTTP 4xx status code error
ERR_BAD_RESPONSEAjaxErrorHTTP 5xx status code error

Browser Support

ChromeFirefoxSafariOperaEdge
Latest ✔Latest ✔Latest ✔Latest ✔Latest ✔

Last updated: