npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

pico-ajax

v1.0.4

Published

A very tiny yet functional ajax library written in TS

Downloads

30

Readme

PicoAjax

Universal, very tiny (browser version is ~1kb uncompressed) yet fully functional AJAX library with zero dependencies. It implements browser XMLHttpRequest and Node.js http/https module returning Promise.

Motivation

What makes Pico-Ajax different is that it's unaware on how data is passed. That requires a few more bytes of code to make a request, but gives much more control and (more important) better understanding of HTTP requests in exchange. This also makes it perfect for building your own DIY API module.

Limitations

Since server implementation is mostly synchronous it's not recommended to use PicoAjax in loaded projects.

Install

Via npm:

npm install --save pico-ajax

then import pico-ajax module

import PicoAjax from 'pico-ajax';
// or if you use CommonJS imports:
const PicoAjax = require('pico-ajax');

Or use as a legacy module (will be available as PicoAjax in a global scope):

<script src="/scripts/picoajax.min.js"></script>

API

PicoAjax exposes all known http methods (connect, delete, get, head, options, patch, post and put) with two arguments: 'url' and 'options'.

First argument is url of type string. Note that you should compose GET parameters by yourself:

  const params = new URLSearchParams({ foo: "bar", page: 2 }).toString();
  const url = `https://example.com?${params}`;

  PicoAjax
    .get(url)
    .then(response => console.log('response received'));

Second argument (options) is a plain object, whose keys override defaults below:

options: {
  body: undefined,        // Request body, see details below
  headers: {},            // Request headers, see details below
  password: undefined,    // HTTP auth password
  user: undefined,        // HTTP auth user
  timeout: undefined,     // Request timeout
  responseType: '',       // [Browser-only] Could be 'json|arraybuffer|blob|document|text',
  async: true,            // [Browser-only] Could be helpful since e.g. workers lack async support
  onProgress: undefined,  // [Browser-only] XMLHttpRequest onprogress callback
  withCredentials: false, // [Browser-only] Whether should send cookies with cross-origin requests
}

PicoAjax http methods return Promises which are resolved with Response object:

response: {
  body: any,                  // Response body, PicoAjax always tries to JSON.parse response body
  headers: Object,            // Response headers
  statusCode: number,         // Response status code, e.g. 200
  statusMessage: string,      // Response status message, e.g. OK
}

In case http didn't succeed (response code other than 2xx, or another error), Promise is rejected with an Error instance with reponse fields added:

error: {
  name: string,               // Error name, e.g. NetworkError
  message: string,            // Error message, e.g. 500 Server Error
  body: any,                  // Response body, PicoAjax always tries to JSON.parse response body
  headers: Object,            // Response headers
  statusCode: number,         // Response status code, e.g. 200
  statusMessage: string,      // Response status message, e.g. OK
}

Usage

You may start right now with a simple GET request:

PicoAjax
  .get('/some/api/?foo=bar&baz=qux')
  .then(({ headers, body }) => {
    console.log(headers, body);
  })
  .catch((error) => {
    console.error(error.message, error.statusCode);
  });

// or if you prefer async/await
try {
  const { headers, body } = await PicoAjax.get('/some/api/?foo=bar&baz=qux');
  console.log(headers, body);
} catch (e) {
  console.error(e.message, e.statusCode);
}

Multipart/form-data

// Prepare form data using DOM form (Browser only)
const formData = new FormData(document.querySelector('form'));

// Or with a plain object 
const foo = { bar: 'baz' };
const formData = new FormData();

Object.keys(foo).forEach(key => {
  formData.append(key, foo[key]);
});

// Perform POST request
PicoAjax
  .post('/some/api/', { body: formData })
  .then(({ headers, body, statusCode }) => {
    console.log(statusCode, headers, body);
  })
  .catch((error) => {
    console.error(error.message, error.statusCode);
  });

JSON

const body = JSON.stringify({ foo: 'bar', baz: 'qux' });
const headers = { 'Content-Type': 'application/json' };

PicoAjax
  .post('/some/api/', { body, headers })
  .then(({ headers, body, statusCode }) => {
    console.log(statusCode, headers, body);
  })
  .catch((error) => {
    console.error(error.message, error.statusCode);
  });

File upload

const formData = new FormData(); 
formData.append('userfile', fileInputElement.files[0]);

PicoAjax
  .post('/some/api/', { body: formData })
  .then(({ headers, body, statusCode }) => {
    console.log(statusCode, headers, body);
  })
  .catch((error) => {
    console.error(error.message, error.statusCode);
  });

Advanced use

If you are going to make quite a few similar requests in your project, you probably may want to make one more layer of abstraction over Pico-Ajax. Please refer to api-example.js module in examples directory.

License

MIT found in LICENSE file.