• Stars
    star
    998
  • Rank 45,938 (Top 1.0 %)
  • Language
    JavaScript
  • Created over 9 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Make JSONP request like window.fetch

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 native 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

JSONP only supports GET method, same as fetch-jsonp.

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 parameter 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 callback function name, default is a random number with json_ prefix

fetchJsonp('/users.jsonp', {
    jsonpCallbackFunction: 'function_name_of_jsonp_response'
  })
  .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,
  })
  .then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('parsed json', json)
  }).catch(function(ex) {
    console.log('parsing failed', ex)
  })

Difference between jsonpCallback and jsonpCallbackFunction

There two functions can easily be confused with each other, but there is a clear distinction.

Default values are

  • jsonpCallback, default value is callback. It's the name of the callback parameter
  • jsonpCallbackFunction, default value is null. It's the name of the callback function. In order to make it distinct, it's a random string with jsonp_ prefix like jsonp_1497658186785_39551. Leave it blank if it's set by the server, set it explicitly if the callback function name is fixed.
Case 1:
fetchJsonp('/users.jsonp', {
  jsonpCallback: 'cb'
})

The request url will be /users.jsonp?cb=jsonp_1497658186785_39551, and the server should respond with a function like:

jsonp_1497658186785_39551(
  { ...data here... }
)
Case 2:
fetchJsonp('/users.jsonp', {
  jsonpCallbackFunction: 'search_results'
})

The request url will be /users.jsonp?callback=search_results, and the server should always respond with a function named search_results like:

search_results(
  { ...data here... }
)

Caveats

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

2. Uncaught SyntaxError: Unexpected token : error

More than likely, you are calling a JSON api, which does not support JSONP. The difference is that JSON api responds with an object like {"data": 123} and will throw the error above when being executed as a function. On the other hand, JSONP will respond with a function wrapped object like jsonp_123132({data: 123}).

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.

More Repositories

1

You-Dont-Need-jQuery

Examples of how to do query, style, dom, ajax, event etc like jQuery with plain javascript.
JavaScript
20,334
star
2

blog

✍️Front-end Development Thoughts
3,665
star
3

react-basic

React 设计思想
1,087
star
4

chrome-github-mate

Chrome extension to make single file download effortless and with more features
JavaScript
360
star
5

chatgpt-engineer-prompts

Awesome ChatGPT prompts for engineers😇
167
star
6

fetch-detector

检测浏览器版本判断是否支持 Fetch
JavaScript
39
star
7

areact

Write React from scratch
JavaScript
35
star
8

react-source-debug

JavaScript
26
star
9

yarn-duplicate

A small tool to help you check package duplicates in `yarn.lock`
JavaScript
17
star
10

babel-npm-boilerplate

A Boilerplate for creating NPM packages using Babel, ESLint, Mocha and Chai
JavaScript
15
star
11

yui.rocket

A JavaScript MVC framework for scalable One-Page-Application using YUI
JavaScript
11
star
12

stock-watch

A simple tool for fetching realtime and historical k-chart data of global stock markets including China.
JavaScript
8
star
13

bravo-bootstrap-rails

A pure gem just adds bootstrap to your Rails project.
Ruby
4
star
14

chrome-headless-test

chrome headless screenshot test
JavaScript
2
star
15

old-rubyer.me

Ruby迷博客
PHP
2
star
16

localStorage-info

💰 Get to know localStorage size & more
JavaScript
2
star
17

ubuntu-ruby-install

My Ubuntu environment for Ruby on Rails
2
star
18

bravo-generators

A collection of useful Rails generator scripts
Ruby
2
star
19

cash-cache

localStorage enhancer with sugar functions and LRU cache
JavaScript
1
star
20

user_auth

Ruby
1
star
21

simple-template

simple js template
JavaScript
1
star
22

camsong

1
star
23

modern-boilerplate

A modern boilerplate with React, Webpack, Babel, Redux, Immutable inside
JavaScript
1
star
24

sinatra-octopress

simply octopress-like blog in sinatra
JavaScript
1
star
25

storex2

localStorage enhancer with sugar functions and LRU cache
JavaScript
1
star