CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-reqwest

A wrapper for asynchronous HTTP requests supporting XMLHttpRequest, JSONP, CORS, and CommonJS Promises

Pending
Overview
Eval results
Files

core-requests.mddocs/

Core Requests

Primary AJAX request functionality providing comprehensive HTTP request capabilities with support for all HTTP methods, multiple data formats, cross-origin requests, and extensive configuration options.

Capabilities

Main Request Function

Creates and executes AJAX requests with flexible configuration options.

/**
 * Creates and executes an AJAX request
 * @param {string|Object} options - URL string or configuration object
 * @param {Function} callback - Optional success callback for URL string form
 * @returns {Object} Request object with promise-like interface
 */
function reqwest(options, callback);

Usage Examples:

// Simple URL form
reqwest('https://api.example.com/data', function(response) {
  console.log('Data:', response);
});

// Full configuration object
reqwest({
  url: 'https://api.example.com/users',
  method: 'POST',
  type: 'json',
  data: { name: 'Alice', email: 'alice@example.com' },
  headers: { 'Authorization': 'Bearer token123' },
  success: function(resp) { console.log('Created:', resp); },
  error: function(xhr, type, err) { console.log('Failed:', err); }
});

HTTP Methods

Supports all standard HTTP methods through the method option.

interface RequestOptions {
  method?: string; // 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS'
}

Usage Examples:

// GET request (default)
reqwest({ url: '/api/users' });

// POST request
reqwest({
  url: '/api/users',
  method: 'POST',
  data: { name: 'Bob', age: 25 }
});

// PUT request
reqwest({
  url: '/api/users/123',
  method: 'PUT',
  data: { name: 'Robert', age: 26 }
});

// DELETE request
reqwest({
  url: '/api/users/123',
  method: 'DELETE'
});

Response Types

Automatic content type detection and manual type specification for various response formats.

interface RequestOptions {
  type?: string; // 'json' | 'xml' | 'html' | 'text' | 'js' | 'jsonp'
}

Usage Examples:

// JSON response (auto-parsed)
reqwest({
  url: '/api/data.json',
  type: 'json',
  success: function(data) {
    console.log(data.users); // Already parsed as JavaScript object
  }
});

// XML response
reqwest({
  url: '/api/data.xml',
  type: 'xml',
  success: function(xmlDoc) {
    const items = xmlDoc.getElementsByTagName('item');
  }
});

// JSONP for cross-domain requests
reqwest({
  url: 'https://external-api.com/data.jsonp?callback=?',
  type: 'jsonp',
  success: function(data) {
    console.log('External data:', data);
  }
});

Request Data

Multiple formats for sending data with requests.

interface RequestOptions {
  data?: any; // Object | string | FormData | Array
  processData?: boolean; // Whether to process data (default: true)
}

Usage Examples:

// Object data (automatically serialized)
reqwest({
  url: '/api/users',
  method: 'POST',
  data: { name: 'Charlie', age: 30 }
});

// Array of name/value pairs
reqwest({
  url: '/api/search',
  method: 'POST',
  data: [
    { name: 'query', value: 'javascript' },
    { name: 'type', value: 'tutorial' }
  ]
});

// Pre-serialized string data
reqwest({
  url: '/api/raw',
  method: 'POST',
  data: 'name=Dave&age=35',
  processData: false
});

// FormData object
const formData = new FormData();
formData.append('file', fileInput.files[0]);
reqwest({
  url: '/api/upload',
  method: 'POST',
  data: formData,
  processData: false
});

Headers and Content Type

Custom headers and content type specification.

interface RequestOptions {
  headers?: Object; // Custom request headers
  contentType?: string; // Request Content-Type header
}

Usage Examples:

// Custom headers
reqwest({
  url: '/api/protected',
  headers: {
    'Authorization': 'Bearer ' + token,
    'X-Custom-Header': 'custom-value',
    'Accept': 'application/json'
  }
});

// JSON content type
reqwest({
  url: '/api/json-endpoint',
  method: 'POST',
  contentType: 'application/json',
  data: JSON.stringify({ key: 'value' }),
  processData: false
});

// Form content type (default)
reqwest({
  url: '/api/form-endpoint',
  method: 'POST',
  contentType: 'application/x-www-form-urlencoded',
  data: { field1: 'value1', field2: 'value2' }
});

Cross-Origin Requests

CORS and credential support for cross-domain requests.

interface RequestOptions {
  crossOrigin?: boolean; // Enable cross-origin requests
  withCredentials?: boolean; // Include credentials in cross-origin requests
}

Usage Examples:

// Basic cross-origin request
reqwest({
  url: 'https://api.external.com/data',
  crossOrigin: true,
  success: function(data) {
    console.log('Cross-origin data:', data);
  }
});

// Cross-origin with credentials (cookies, auth)
reqwest({
  url: 'https://secure.external.com/user-data',
  crossOrigin: true,
  withCredentials: true,
  headers: { 'Authorization': 'Bearer ' + token }
});

JSONP Configuration

Specialized configuration for JSONP requests.

interface RequestOptions {
  jsonpCallback?: string; // JSONP callback parameter name
  jsonpCallbackName?: string; // Specific callback function name
}

Usage Examples:

// Automatic JSONP callback
reqwest({
  url: 'https://api.example.com/data.jsonp?callback=?',
  type: 'jsonp',
  success: function(data) {
    console.log('JSONP data:', data);
  }
});

// Custom callback parameter name
reqwest({
  url: 'https://api.example.com/data.jsonp',
  type: 'jsonp',
  jsonpCallback: 'mycallback', // Uses ?mycallback=reqwest_12345
  success: function(data) {
    console.log('JSONP data:', data);
  }
});

// Specific callback function name
reqwest({
  url: 'https://api.example.com/data.jsonp?cb=handleData',
  type: 'jsonp',
  jsonpCallback: 'cb',
  jsonpCallbackName: 'handleData',
  success: function(data) {
    console.log('JSONP data:', data);
  }
});

Advanced Configuration

Additional configuration options for specialized use cases.

interface RequestOptions {
  timeout?: number; // Request timeout in milliseconds
  async?: boolean; // Asynchronous flag (default: true)
  xhr?: Function; // Custom XHR factory function
  before?: Function; // Pre-request callback with XHR object
  dataFilter?: Function; // Response filtering function
}

Usage Examples:

// Request timeout
reqwest({
  url: '/api/slow-endpoint',
  timeout: 10000, // 10 seconds
  error: function(xhr, type, err) {
    if (type === 'timeout') {
      console.log('Request timed out');
    }
  }
});

// Custom XHR factory
reqwest({
  url: '/api/data',
  xhr: function() {
    const xhr = new XMLHttpRequest();
    xhr.upload.onprogress = function(e) {
      console.log('Upload progress:', (e.loaded / e.total) * 100 + '%');
    };
    return xhr;
  }
});

// Pre-request processing
reqwest({
  url: '/api/data',
  before: function(xhr) {
    xhr.setRequestHeader('X-Timestamp', Date.now());
    console.log('About to send request');
  }
});

// Response filtering
reqwest({
  url: '/api/wrapped-data',
  type: 'json',
  dataFilter: function(data, type) {
    // Remove wrapper from API response
    return type === 'json' ? data.result : data;
  }
});

Request Object Methods

The object returned by reqwest() provides additional control methods:

Abort Request

/**
 * Aborts the current request
 * @returns {Object} Self for chaining
 */
abort(): RequestPromise;

Retry Request

/**
 * Retries the request with the same options
 * @returns {Object} Self for chaining
 */
retry(): RequestPromise;

Usage Examples:

// Abort request
const request = reqwest({ url: '/api/large-data' });
setTimeout(() => {
  request.abort();
}, 5000);

// Retry failed request
reqwest({ url: '/api/unreliable' })
  .fail(function(xhr, type, err) {
    console.log('First attempt failed, retrying...');
    return this.retry();
  })
  .then(function(data) {
    console.log('Success on retry:', data);
  });

Install with Tessl CLI

npx tessl i tessl/npm-reqwest

docs

core-requests.md

index.md

jquery-compat.md

promise-interface.md

utilities.md

tile.json