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

owp.http

v3.1.0

Published

HTTP client for JavaScript

Downloads

18

Readme

OpenWebProject HTTP

HTTP client for JavaScript

HTTP is a simple and lightweight wrapper for the browsers native XMLHttpRequest functionality.
The purpose of this utility is to easiliy enable HTTP request without relying on a large framework. No matter if you have a simple standard JS app, uses jQuery or react framework you can make use of HTTP request in the same way.

Installation and use

npm install owp.http --save
import HTTP from "owp.http";

Static requests

HTTP.useOptions(options);
const promise = HTTP.get("http://www.mysite.com/rest/data", options);
const promise = HTTP.delete("http://www.mysite.com/rest/data", options);
const promise = HTTP.head("http://www.mysite.com/rest/data", options);
const promise = HTTP.post("http://www.mysite.com/rest/data", options);
const promise = HTTP.put("http://www.mysite.com/rest/data", options);
const promise = HTTP.patch("http://www.mysite.com/rest/data", options);
const promise = HTTP.jsonp("http://www.mysite.com/rest/data", options);

Instance requests

HTTP.useOptions(options);
const http = new HTTP("http://www.mysite.com/rest", options);
const promise = http.get("data", options);
const promise = http.delete("data", options);
const promise = http.head("data", options);
const promise = http.post("data", options);
const promise = http.put("data", options);
const promise = http.patch("data", options);
const promise = http.jsonp("data", options);

Options

| Name | Description | | ---------------------- | ------------------------------------- | | headers | Headers | | params | Query parameters | | data | Data payload | | json | JSON data payload | | fullResponse | Set to true to get full response | | contentType | Media type(MIME) for data payload | | responseType | Type for response data | | cache | Set to true to cache responses | | stateChangeInterceptor | State change interceptor callback | | requestInterceptor | Request interceptor callback | | responseInterceptor | Response interceptor callback | | download | Set to true to download response data | | filename | Filename for downloaded file |

Options inheritence

  • Add options to the class with useOptions(options)
    • Inherits NO options
  • Add options to the static request HTTP.get("URL", options)
    • Inherits CLASS options
  • Add options to the instance new HTTP("URL", options)
    • Inherits CLASS options
  • Add options to the instance request http.get("PATH", options)
    • Inherits INSTANCE options

Path parameters

const id = "Fo%Bar";

//Static request. All paths string after the first(base) one is uri encoded.
const promise = HTTP.get("http://www.mysite.com/rest/data", id, "subpath");

//Instance constructor. All paths string after the first(base) one is uri encoded.
const http = new HTTP("http://www.mysite.com", "rest");
//Instance request. All path string are uri encoded.
const promise = http.get("data", id, "subpath");
//Instance request at base path.
const promise = http.get();

Headers and query parameters

//Headers. Flat object(key/value map)
const headers = { Origin: "http://www.mysite.com" };

//Query parameters. Object(key/value map) which supports multiple values per key.
//?id=123&field=name&field=value
const params = { id: "123", field: ["name", "value"] };

//Can be used for static requests.
const promise = HTTP.get("http://www.mysite.com/rest/data", { headers: headers, params: params });

//Can be given to the constructor and passed to each request.
const http = new HTTP("http://www.mysite.com/rest", { headers: headers, params: params });

//Can be defined for single request.
const promise = http.get("data", { headers: headers, params: params });

Payload

Payload parameters are the same for post/put/patch.

//Data with specified content type.
const promise = http.post({ data: "myData", contentType: "text/plain" });
//Data with undefined content type. String/boolean/number defaults to "text/plain".
const promise = http.post({ data: "myData" });
//Unspecified objects are converted to urlencoded query string a=1&b=2 with content type: "application/x-www-form-urlencoded".
const promise = http.post({ data: { a: 1, b: 2 } });
//Json object. Object is stringified and content type is "application/json".
const promise = http.post({ json: { a: 1, b: 2 } });

Response

Resolved promise returns payload.

http.get()
    .then(function (response) {
        //Response from server if promise resolved(request succeeded).
    })
    .catch(function (error) {
        //Full response object if promise rejected(request failed). Se  below for description of full response.
    });

Full response

Get a full response in both promise resolve and reject.

http.get({ fullResponse: true })
    .then(function(response) {
        //Full response returned.
    });

//Full response format.
{
    ok: true,
    url: "http://www.mysite.com/rest/data?id=123",
    status: 200,
    statusText: "OK",
    text: "{ value: 5 }",
    //Data is the same value that is returned in a simple(non full) response.
    data: { value: 5 },
    //Object with headers
    headers: { }
}

Response type

Specify response type. Can be used to request binary data

http.get({ responseType: "blob" }).then(function (blob) {
    //Blob containing binary data
});

Cache

Enable cache. Matches method+url and caches response.

http.get({ cache: true }).then(function (cachedResponse) {
    //Response is fetched from cache.
});

State change interceptor

Callback to trigger on every state change on the underlying XMLHttp​Request​.
0 UNSENT - Client has been created. open() not called yet.
1 OPENED - open() has been called.
2 HEADERS_RECEIVED - send() has been called, and headers and status are available.
3 LOADING - Downloading; responseText holds partial data.
4 DONE - The operation is complete.

stateChangeInterceptor: function (readyState) {
    switch (readyState) {
        //readyState = [0, 4]
    }
};

Request interceptor

Callback to format/update request. Useful for updating auth credentials.

requestInterceptor: function(request: object) {
    //Update auth credentials
    request.headers.Authorization = "...";
    //Return updated request
    return request;
    //Or return Promise.
    return Promise.resolve(request);
    //Returning rejected promise rejects the entire http request.
    return Promise.reject("Error");
}

Response interceptor

Callback to format/update response. Useful for logging errors.

responseInterceptor: function(response: object) {
    //Change response
    if (response.data === null) {
        response.data = "No Data, but ok";
    }
    //Log errors
    if (!response.ok) {
        console.error(response.statusText);
    }
    //Return updated response.
    return response;
    //Or return Promise.
    return Promise.resolve(response);
    //Returning rejected promise rejects the entire http request.
    return Promise.reject("Error");
}