1.12.0 • Published 2 years ago

@seven_y_q_guo/jsonp v1.12.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

<CircleCI>

build-your-own JSONP

Inspired from https://github.com/webmodules/jsonp

Installation

Install via NPM:

npm i @seven_y_q_guo/jsonp

Usage

const jsonp = require("@seven_y_q_guo/jsonp"); // or import jsonp from '@seven_y_q_guo/jsonp';

jsonp('http://jsfiddle.net/echo/jsonp?name=seven', {
  name: 'hello',
  success: (info) => {
    console.log(info); // {name: 'seven'}
  },
  error: (error) => {
    console.log(error); // handle kinds of errors like timeout, 404, etc.
  }
});

API

jsonp(url, opts)

  • url (String) url to fetch
  • opts (Object)
    • success handle success
    • error handle error
    • param (String) name of the query string parameter to specify the callback (defaults to callback)
    • timeout (Number) how long after a timeout error is emitted. 0 or other falsy value to disable (defaults to 30000)
    • prefix (String) prefix for the global callback functions that handle jsonp responses (defaults to __jp)
    • name (String) optional: name of the global callback functions that handle jsonp responses, will generate __jp + incremented counter if not passing specific name

Returns a function that, when called, will cancel the in-progress jsonp request (success & error won't be called any more).

Want Promise?

You can implement easily

function fetchJson(url, opts = {}) {
  return new Promise((resolve, reject) => {
    jsonp(url, {
      ...opts,
      success: resolve,
      error: reject
    });
  })
}

fetchJson('http://jsfiddle.net/echo/jsonp?name=seven').then(res => {
  console.log(res);
}).catch(err => {
  console.log(err);
});

License

MIT

1.12.0

2 years ago

1.11.0

2 years ago

1.10.0

2 years ago

1.9.0

2 years ago

1.8.0

2 years ago

1.7.0

2 years ago

1.6.0

2 years ago

1.5.0

2 years ago

1.4.0

2 years ago

1.3.0

2 years ago

1.2.0

2 years ago

1.1.0

2 years ago

1.0.0

2 years ago