1 | # Fetch JSONP like a boss using Fetch API
|
2 |
|
3 | JSONP is NOT supported in standard Fetch API, https://fetch.spec.whatwg.org.
|
4 | fetch-jsonp provides you same API to fetch JSONP like naive Fetch, also comes
|
5 | with global `fetchJsonp` function.
|
6 |
|
7 | If you need a `fetch` polyfill for legacy browsers, try [github/fetch](github.com/github/fetch).
|
8 |
|
9 | ## Installation
|
10 |
|
11 | You can install with `npm`.
|
12 |
|
13 | You'll also need a Promise polyfill for [legacy browsers](http://caniuse.com/#feat=promises).
|
14 |
|
15 | ```sh
|
16 | $ bower install es6-promise
|
17 | ```
|
18 |
|
19 | Also available on [Bower](http://bower.io) as **fetch-jsonp**
|
20 |
|
21 | ```sh
|
22 | $ bower install fetch-jsonp
|
23 | ```
|
24 |
|
25 | ## Usage
|
26 |
|
27 | The `fetch-jsonp` function supports any HTTP method. We'll focus on GET and POST
|
28 | example requests.
|
29 |
|
30 | ### Fetch JSONP in simple way
|
31 |
|
32 | ```javascript
|
33 | fetchJsonp('/users.jsonp')
|
34 | .then(function(response) {
|
35 | return response.json()
|
36 | }).then(function(json) {
|
37 | console.log('parsed json', json)
|
38 | }).catch(function(ex) {
|
39 | console.log('parsing failed', ex)
|
40 | })
|
41 | ```
|
42 |
|
43 | ### Set JSONP callback name, default is 'callback'
|
44 |
|
45 | ```javascript
|
46 | fetchJsonp('/users.jsonp', {
|
47 | jsonpCallback: 'custom_callback'
|
48 | })
|
49 | .then(function(response) {
|
50 | return response.json()
|
51 | }).then(function(json) {
|
52 | console.log('parsed json', json)
|
53 | }).catch(function(ex) {
|
54 | console.log('parsing failed', ex)
|
55 | })
|
56 | ```
|
57 |
|
58 | ### Set JSONP request timeout, default is 5000ms
|
59 |
|
60 | ```javascript
|
61 | fetchJsonp('/users.jsonp', {
|
62 | jsonpCallback: 'custom_callback'
|
63 | })
|
64 | .then(function(response) {
|
65 | return response.json()
|
66 | }).then(function(json) {
|
67 | console.log('parsed json', json)
|
68 | }).catch(function(ex) {
|
69 | console.log('parsing failed', ex)
|
70 | })
|
71 | ```
|
72 |
|
73 | ### Caveats
|
74 |
|
75 | You need to call `.then(function(respons) { return respons.json(); })` in order
|
76 | to keep consistent with Fetch API.
|
77 |
|
78 | ## Browser Support
|
79 |
|
80 | ![Chrome](https://raw.github.com/alrra/browser-logos/master/chrome/chrome_48x48.png) | ![Firefox](https://raw.github.com/alrra/browser-logos/master/firefox/firefox_48x48.png) | ![IE](https://raw.github.com/alrra/browser-logos/master/internet-explorer/internet-explorer_48x48.png) | ![Opera](https://raw.github.com/alrra/browser-logos/master/opera/opera_48x48.png) | ![Safari](https://raw.github.com/alrra/browser-logos/master/safari/safari_48x48.png)
|
81 | --- | --- | --- | --- | --- |
|
82 | Latest ✔ | Latest ✔ | 9+ ✔ | Latest ✔ | 6.1+ ✔ |
|