1.0.1 • Published 2 years ago
@amy1994/jsonp v1.0.1
build-your-own JSONP
Inspired from https://github.com/webmodules/jsonp
Installation
Install via NPM:
npm i @amy/jsonp
Usage
const jsonp = require("@amy/jsonp"); // or import jsonp from '@amy/jsonp';
jsonp('http://jsfiddle.net/echo/jsonp?name=amy', {
name: 'hello',
success: (info) => {
console.log(info); // {name: 'amy'}
},
error: (error) => {
console.log(error); // handle kinds of errors like timeout, 404, etc.
}
});
API
jsonp(url, opts)
url
(String
) url to fetchopts
(Object
)success
handle successerror
handle errorparam
(String
) name of the query string parameter to specify the callback (defaults tocallback
)timeout
(Number
) how long after a timeout error is emitted.0
or other falsy value to disable (defaults to30000
)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=amy').then(res => {
console.log(res);
}).catch(err => {
console.log(err);
});
License
MIT