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

req-json

v2.3.2

Published

Promise based simple HTTP/HTTPS client for browser to request JSON or string for RESTful apis, with koa-like middleware support.

Downloads

30

Readme

req-json

npm bundle size npm downloads license

github build coverage

Promise based simple HTTP/HTTPS client for browser to request JSON or string for RESTful apis, with koa-like middleware support.

Documents and examples.

Installation

NPM

npm install req-json --save
import ReqJSON from 'req-json';

Browser

Direct <script> include

<script src="https://cdn.jsdelivr.net/npm/req-json@2"></script>

Wechat mini program (weapp)

const ReqJSON = require('req-json/dist/req-json.wx');

or just download and copy to your project.

Basic Usage

import ReqJSON from 'req-json';

const reqJSON = new ReqJSON();

reqJSON.get('/api/item/:id', { id: 1 })
  .then((item) => {});

Shorthand methods

async getItem(id) {
  let item;
  try {
    item = await reqJSON.get('/api/item/:id', { id });
  } catch (err) {
    console.error(err);
  }
  return item;
}

async updateItem(item) {
  try {
    await reqJSON.post('/api/item/:id', item);
  } catch (err) {
    console.error(err);
  }
}

RESTful API

const resource = reqJSON.resource('/api/item/:id');

async getItem(id) {
  let item;
  try {
    item = await resource.get({ id });
  } catch (err) {
    console.error(err);
  }
  return item;
}

async updateItem(item) {
  try {
    await resource.post(item);
  } catch (err) {
    console.error(err);
  }
}

Methods

Supports GET POST PUT DELETE methods.

const resource = reqJSON.resource('/api/item/:id');

async request() {
  try {
    const response = await resource.get({ id: 1 });
    await resource.post({
      id: 1,
      others: { foo: 'bar' }
    });
    await resource.put({
      id: 1,
      others: { foo: 'bar' }
    });
    await resource.delete({ id: 1 });
  } catch (err) {
    console.error(err);
  }
}

Options

You can set option for ReqJSON instance / resource defination / each single request.

  • headers: Customized request headers
  • timeout: Set request timeout

Set option for ReqJSON instance

const options = {
  headers: {
    Authorization: 'abc'
  },
  timeout: 1000
};
const reqJSON = new ReqJSON(options);

Set option for resource defination.

const options = {
  headers: {
    Authorization: 'abc'
  },
  timeout: 1000
};
const resource = reqJSON.resource('/api/item/:id', options);

async request() {
  try {
    await resource.get({ id: 1 });
  } catch (err) {
    console.error(err);
  }
}

Set option for single request.

async request() {
  const options = {
    headers: {
      Authorization: 'abc'
    },
    timeout: 1000
  };
  try {
    await resource.get({ id: 1 }, options);
  } catch (err) {
    console.error(err);
  }
}

Middlewares

Supports two diffrent kinds of functions as middleware:

  • async function
  • common function

Async function (Can I use)

reqJSON.use(async(context, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  console.log(`${context.method} ${context.url} ${ms}ms`);
});

Common function

reqJSON.use((context, next) => {
  const start = Date.now();
  return next()
    .then(() => {
      const ms = Date.now() - start;
      console.log(`${context.method} ${context.url} ${ms}ms`);
    });
});

Context

Context contains these attributes:

/**
 * The path to use for the request, with parameters defined.
 */
path: string

/**
 * The HTTP method to use for the request (e.g. "POST", "GET", "PUT", "DELETE").
 */
method: 'POST' | 'GET' | 'PUT' | 'DELETE'

/**
 * The URL to which the request is sent.
 */
url: string

/**
 * The data to be sent.
 */
data: any

/**
 * The options to use for the request.
 */
options: object

/**
 * The HTTP status of the response. Only available when the request completes.
 */
status?: number

/**
 * The parsed response. Only available when the request completes.
 */
response?: any

/**
 * The request headers before the request is sent, the response headers when the request completes.
 */
headers: Headers

/**
 * Alias to `headers`
 */
header: Headers

/**
 * The original XMLHttpRequest object.
 */
xhr: XMLHttpRequest

Reject when status 4xx or 5xx

Async function

reqJSON.use(async(context, next) => {
  await next();
  if (context.status >= 400) {
    throw new Error(context.response);
  }
});

Common function

reqJSON.use((context, next) => {
  return next()
    .then(() => {
      if (context.status >= 400) {
throw new Error(context.response);
      }
    });
});

Set request headers and get response headers

Async function

reqJSON.use(async(context, next) => {
  // set request headers
  context.headers = {
    'If-None-Match': 'abcdefg'
  };
  await next();
  // get response headers
  console.log(context.headers.etag);
});

Common function

reqJSON.use((context, next) => {
  // set request headers
  context.headers = {
    'If-None-Match': 'abcdefg'
  };
  return next()
    .then(() => {
      // get response headers
      console.log(context.headers.etag);
    });
});