Make JSONP request like window.fetch
JavaScript
Latest commit af61322 Dec 29, 2016 @camsong release 1.0.5
Permalink
Failed to load latest commit information.
build release 1.0.3 Dec 4, 2016
examples release index-ie8 Dec 4, 2016
src fix #11: use original url when Request error Sep 26, 2016
test First commit Aug 8, 2015
.eslintrc First commit Aug 8, 2015
.gitignore First commit Aug 8, 2015
.npmignore First commit Aug 8, 2015
.travis.yml First commit Aug 8, 2015
HISTORY.md release 1.0.5 Dec 29, 2016
MAINTAINING.md remove bower support Nov 19, 2015
README.md update Nov 16, 2016
index.d.ts optimize typescript d.ts Dec 29, 2016
package.json release 1.0.5 Dec 29, 2016

README.md

Fetch JSONP Build Status npm version npm downloads

JSONP is NOT supported in standard Fetch API, https://fetch.spec.whatwg.org. fetch-jsonp provides you same API to fetch JSONP like naive Fetch, also comes with global fetchJsonp function.

If you need a fetch polyfill for old browsers, try github/fetch.

Installation

You can install with npm.

npm install fetch-jsonp

Promise Polyfill for IE

IE8/9/10/11 does not support ES6 Promise, run this to polyfill the global environment at the beginning of your application.

require('es6-promise').polyfill();

Usage

The fetch-jsonp function supports any HTTP method. We'll focus on GET and POST example requests.

Fetch JSONP in simple way

fetchJsonp('/users.jsonp')
  .then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('parsed json', json)
  }).catch(function(ex) {
    console.log('parsing failed', ex)
  })

Set JSONP callback name, default is 'callback'

fetchJsonp('/users.jsonp', {
    jsonpCallback: 'custom_callback'
  })
  .then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('parsed json', json)
  }).catch(function(ex) {
    console.log('parsing failed', ex)
  })

Set JSONP request timeout, default is 5000ms

fetchJsonp('/users.jsonp', {
    timeout: 3000,
    jsonpCallback: 'custom_callback'
  })
  .then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('parsed json', json)
  }).catch(function(ex) {
    console.log('parsing failed', ex)
  })

Caveats

You need to call .then(function(response) { return response.json(); }) in order to keep consistent with Fetch API.

Browser Support

Chrome Firefox IE Opera Safari
Latest ✔ Latest ✔ 8+ ✔ Latest ✔ 6.1+ ✔

License

MIT

Acknowledgement

Thanks to github/fetch for bring Fetch to old browsers.