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

phax

v4.0.2

Published

Lightweight HTTP client based on the browser Fetch API

Downloads

2

Readme

phax

phax is a lightweight HTTP client based on the browser Fetch API;

Language

  1. English
  2. 简体中文

Installing

npm install phax --save
// or
yarn add phax

Usage

Temporarily only supports GET/POST/PUT/PATCH/HEAD/DELETE method. The default value:

{
  credentials: 'same-origin',
  method: 'GET'
}
import phax from 'phax'; // ES6 module

window.phax.get;
window.phax.post;
// or
phax.get;
phax.post;

// add interceptor
// add request interceptor
phax.interceptors.request(function (params) {
  params.json.b = 2;
  return params;
});
// add response interceptor, first function response interceptor,second function error interceptor
phax.interceptors.response(
  function (params) {
    return params;
  },
  (err: PhaxError) => {}
);

phax
  .get()
  .then(function (res) {
    // Response.ok == true
    console.log(res);
  })
  .catch(function (err) {
    if (err.name === 'StatusError') {
      // HTTP statuses error
      console.log(err.statusCode + ' & ' + err.message);
    } else {
      // Network error
      console.log(err);
    }
  });

The default return value type matches by res.headers.Content-Type,egg:

if (res.headers.Content - Type === 'application/json') {
  return res.json();
}

Return type matching:

  1. text/* => text
  2. application/json => json
  3. multipart/form-data => formData

Different from native API. phax's catch error contains Network errorHTTP statuses error. For function parameters refer to fetch-polyfill or fetch

Example

GET

Performing a GET request.

import phax from 'phax';

phax({
  url: '/user?id=1',
  method: 'GET',
});

phax
  .get('/user?id=1')
  .then(function (res) {
    console.log(res); // json
  })
  .catch(function (err) {
    console.log(err);
  });

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await phax.get('/user?id=12345').json();
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

NOTE: async/await is part of ECMAScript 2017 and is not supported in Internet Explorer and older browsers, so use with caution.

POST

Send json data.

phax.post('/post_user', { json: { name: 'LIVI' } });

Using application/x-www-form-urlencoded format

To send data in the application/x-www-form-urlencoded, you can use one of the following options.

  1. Use the URLSearchParams API as follows:

    var params = new URLSearchParams();
    params.append('param1', 'value1');
    params.append('param2', 'value2');
    
    phax.post('/foo', { body: params });

    Note that URLSearchParams is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).

  2. You can encode data using the qs library:

    phax.post('/foo', {
      headers: { 'content-type': 'application/x-www-form-urlencoded' },
      body: qs.stringify({ bar: 123 }),
    });
  3. If you won't use qs, you can handle the parameters manually:

    var params = 'bar=123&name=LIVI&age=18';
    
    phax.post('/foo', {
      headers: { 'content-type': 'application/x-www-form-urlencoded' },
      body: params,
    });

    NOTE: Follow-up may consider simple support for this approach.

API

  1. phax(url[, accept [, fetchOpts]])
  2. phax(fetchOpts)
  3. phax.get()
  4. phax.post()
  5. phax.interceptors.request()
  6. phax.interceptors.response(() => {}, () => {})

……

supported methods:getpostputdeletepatch,all methods params same as phax() param desc:

  • url: String
  • accept: String [Optional] The return type;The priority over default automatic matching
  • json: Object [Optional] POST JSON body
  • fetchOpts: Object The native fetch supported data,simultaneously compatible with the above three parameters

interceptors add request interceptor:

  • interceptors.request: (cb: (params: PhaxRequestConfig) => PhaxRequestConfig) => void; regist request interceptor,for each request start to operate request params.
  • interceptors.response: (cb: (params: any) => any, err?: (err: PhaxError) => void) => void;:add response interceptor; The first function is response interceptor; The second function is error interceptor.

Promises

phax depends on a native ES6 Promise implementation to be supported. If your environment doesn't support ES6 Promises, you can polyfill. Recommended to use the jsdelivr CDN.

<script src='https://cdn.jsdelivr.net/npm/[email protected]/dist/es6-promise.auto.min.js'></script>

fetch

phax depends on a native fetch API implementation to be supported. If your environment doesn't support fetch, you can polyfill. Recommended to use the jsdelivr CDN.

<script src='https://cdn.jsdelivr.net/npm/[email protected]/dist/fetch.umd.min.js'></script>

TypeScript

phax includes TypeScript definitions.

import phax from 'phax';

phax({ url: '/test?id=1', accept: 'json' }); // get

phax.get('/test?id=1', 'json'); // get

phax.post('/post', 'json'); // post

phax({
  url: '/foo',
  method: 'post',
}); // post

License

MIT