Code Monkey home page Code Monkey logo

fetch-jsonp's Introduction

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.

fetch-jsonp's People

Contributors

awerlang avatar bitdeli-chef avatar bluscale4 avatar briganti avatar camsong avatar eugenioclrc avatar guilhermehubner avatar jiaoguanwen avatar jonathanconway avatar jpierson avatar kukushouhou avatar mstommytan avatar paolodm avatar stfsy avatar timothy-bailey-redbox avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fetch-jsonp's Issues

Uncaught ReferenceError: jsonCallback is not defined

I try to consume an API that returns a function called jsonCallback,
I put the following code and return the error

var fetchJsonp = require("fetch-jsonp") fetchJsonp("http://opendata.euskadi.eus/contenidos/ds_recursos_turisticos/albergues_de_euskadi/opendata/alojamientos.json", { jsonpCallback: 'jsonCallback', }) .then(function(response) { return response.json() }).then(function(json) { console.log('parsed json', json) }).catch(function(ex) { console.log('parsing failed', ex) })

If I look in the header of the request, I see that it happens as a parameter a random callback function.

captura

I'm probably doing something wrong,

Some solution or idea.

Thank you

error in ie8

When I use the example of ie8(index-ie8.html)it report an error:
TypeError: 对象不支持此属性或方法
image

Multiple requests - being silently aborted and throwing timeouts etc?

Hi guys,

New to jsonp - but Im using it to fetch a list of options for an autocomplete input - so as a user types we send the value to the endpoint - and depending on how fast they type, we may end up with a half dozen requests within the default 5000ms timeout for the first request - and from what I can see, only the latest request ends up getting a response - and the others timeout.

Other than throttling the requests from the front end - is there a better way to handle these silent aborts?

Any advice appreciated!

[BUG] There is no jsonCallbackFunction

The documentation refers to jsonCallbackFunction however the parameter is actually named jsonpCallbackFunction (note additional p) in code.

I had to figure out by reading the code, otherwise following the README, it wouldn't work.

:two-cents:

fetch-jsonp

  • I want add cookie in request header , what should I do?

Using headers not possible?

Hi there, thanks for this awesome library.

I'm having trouble using your library while adding a header.
First what I usually do using jQuery:
$.ajax({ url : 'https://api.imgur.com/3/gallery/t/cats/45', type : 'GET', dataType: 'json', headers: { Authorization: 'Client-ID ' + IMGUR_API_CLIENT_ID }, success: function(json) { for (let item of json.data.items) { console.log(item); } });

and now using fetchJsonp:
`let galleryURL = 'https://api.imgur.com/3/gallery/t/cats/45';

fetchJsonp(galleryURL, {
url: galleryURL,
method: 'get',
dataType: 'json',
headers: {
Authorization: 'Client-ID ' + IMGUR_API_CLIENT_ID
}
}).then(function(response) {
return response.json();
}).then(function(json) {
console.log(json);
});`

Can you help me, am I doing something wrong? Are headers supported by fetch-jsonp?
Thanks a lot

Edit: I'm using this combined with aurelia,js and I'm getting a
"Unhandled rejection Error: JSONP request to https://api.imgur.com/3/gallery/t/cats/45 timed out"-Error

IE -> Promise not defined

I tried this on IE and it is giving a console error of Promise not defined. I only tried on IE 10 and 11. It is working on every other browser though.

how to import?

import * as jsonp from 'fetch-jsonp'

console.log(jsonp) //{default: undefined}

so, how to import it?

Handling 403, 404 errors

Currently, if the request fails, it just gets classified as a timeout. Is there any plans to handle 400 errors?

parsing failed Error: JSONP request to 'xxx ' timed out at fetch-jsonp.js:85

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

数据也能返回
image
浏览器控制台
image

请问下我该怎么解决这个问题,还是我没有写正确

Provide an esm version

Currently the only supported module format is UMD. Unfortunately this adds a few paths that might be unexpected for a bundled ESM app.

Can we have a build in ESM module format in addition to the current UMD format? An ESM module should be declared in package.json in attribute module.

Trying to use fetch-jsonp to fech TEXT only value

Hello:

How can I use your script to fetch a URL which response will be a string of characters from a remote server, which otherwise could not work under the usual method.

sample response:

artist - track title (album)

Regards

Place callback parameter first inline

So I've encountered endpoints that require the callback parameter to be first in the url query. The way you're doing it now, the callback always ends up last. My suggestion would be to allow choosing at what position it gets inserted, or always place it first directly after the "?".

If I find the time I will make a pull-request.

Uncaught SyntaxError: Unexpected token :

I'm probably doing something wrong.

I have this:

    fetchJsonp(url, {
        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)
      });

But I'm getting this error:
Uncaught SyntaxError: Unexpected token : on my fetched URL.

Thank you!

Optional callback on URL

I'm using fetchJsonp like so to access data on a resource which I have no control of...

  fetchJsonp(url, {
    method: 'GET',
    mode: 'no-cors',
    credentials: 'include',
  })
    .then(function (data) {
      return data.json();
    })
    .then(function (response) {
      $scope[dateTime] = new Date(response.timestamp * 1000).toLocaleString();
 // ... more code

However, due to fetchJsonp adding a callback query string on the request URL, my request fails:

Error: JSONP request to https://resource.com/api/param1/param1 timed out at fetch-jsonp.js:85

Actual network request:

https://resource.com/api/param1/param1?callback=jsonp_1514919479266_12080

Is there a way for me to remove the callback on the request url due to this case?

Required options

PR #65 has introduced a breaking change to the typing. nonce and referrerPolicy should be optional but have been listed as required fields on the options type. It should be possible to not specify these values.

Library does not support nonce

Hi. Library has worked great so far, but does not respect a nonce value so our Urls cannot be added to the page. i.e. when the nonce value is set, every script added to the page must use the known nonce value.

Ideally we need this added:
if (options.nonce) {
jsonpScript.setAttribute('nonce', options.nonce);
}

Thanks!
Tyler

Catch redirect response ?

Hello,

First of all, thank you for your work.

I was wondering if it's possible to catch a "location" header in the response or a redirect ? Because for now I got a time-out response whereas having the redirect.

Thank you :)

typescript declare error

ERROR in /Users/jere/jm/jumei-sdk/node_modules/fetch-jsonp/index.d.ts (1,73): error TS2304: Cannot find name 'Promise'.

npm install error

I tried installing this package as I need it to make calls to the Instagram API, but on an npm install I get the following errors:

0 info it worked if it ends with ok
1 verbose cli [ '/Users/reinierkaper/.nvm/versions/node/v4.8.2/bin/node',
1 verbose cli   '/Users/reinierkaper/.nvm/versions/node/v4.8.2/bin/npm',
1 verbose cli   'install',
1 verbose cli   '--save',
1 verbose cli   'fetch-jsonp' ]
2 info using [email protected]
3 info using [email protected]
4 silly install loadCurrentTree
5 silly install readLocalPackageData
6 http fetch GET 200 https://registry.npmjs.org/fetch-jsonp 232ms
7 silly pacote range manifest for fetch-jsonp@^1.0.6 fetched in 270ms
8 silly install loadIdealTree
9 silly install cloneCurrentTreeToIdealTree
10 silly install loadShrinkwrap
11 verbose stack SyntaxError: Unexpected token <
11 verbose stack     at Object.parse (native)
11 verbose stack     at module.exports (/Users/reinierkaper/.nvm/versions/node/v4.8.2/lib/node_modules/npm/lib/utils/parse-json.js:3:15)
11 verbose stack     at /Users/reinierkaper/.nvm/versions/node/v4.8.2/lib/node_modules/npm/lib/install/read-shrinkwrap.js:31:20
11 verbose stack     at tryCatcher (/Users/reinierkaper/.nvm/versions/node/v4.8.2/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23)
11 verbose stack     at Holder$3._callFunction (eval at <anonymous> (/Users/reinierkaper/.nvm/versions/node/v4.8.2/lib/node_modules/npm/node_modules/bluebird/js/release/join.js:1:0), <anonymous>:14:44)
11 verbose stack     at Holder$3.checkFulfillment (eval at <anonymous> (/Users/reinierkaper/.nvm/versions/node/v4.8.2/lib/node_modules/npm/node_modules/bluebird/js/release/join.js:1:0), <anonymous>:29:30)
11 verbose stack     at Promise.eval (eval at <anonymous> (/Users/reinierkaper/.nvm/versions/node/v4.8.2/lib/node_modules/npm/node_modules/bluebird/js/release/join.js:1:0), <anonymous>:6:20)
11 verbose stack     at Promise._settlePromise (/Users/reinierkaper/.nvm/versions/node/v4.8.2/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:566:21)
11 verbose stack     at Promise._settlePromise0 (/Users/reinierkaper/.nvm/versions/node/v4.8.2/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:614:10)
11 verbose stack     at Promise._settlePromises (/Users/reinierkaper/.nvm/versions/node/v4.8.2/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:693:18)
11 verbose stack     at Promise._fulfill (/Users/reinierkaper/.nvm/versions/node/v4.8.2/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:638:18)
11 verbose stack     at Promise._settlePromise (/Users/reinierkaper/.nvm/versions/node/v4.8.2/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:582:21)
11 verbose stack     at Promise._settlePromise0 (/Users/reinierkaper/.nvm/versions/node/v4.8.2/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:614:10)
11 verbose stack     at Promise._settlePromises (/Users/reinierkaper/.nvm/versions/node/v4.8.2/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:693:18)
11 verbose stack     at Promise._fulfill (/Users/reinierkaper/.nvm/versions/node/v4.8.2/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:638:18)
11 verbose stack     at /Users/reinierkaper/.nvm/versions/node/v4.8.2/lib/node_modules/npm/node_modules/bluebird/js/release/nodeback.js:42:21
12 verbose cwd /Users/reinierkaper/projects/docker/canvaspop
13 verbose Darwin 16.6.0
14 verbose argv "/Users/reinierkaper/.nvm/versions/node/v4.8.2/bin/node" "/Users/reinierkaper/.nvm/versions/node/v4.8.2/bin/npm" "install" "--save" "fetch-jsonp"
15 verbose node v4.8.2
16 verbose npm  v5.0.0
17 error Unexpected token <
18 verbose exit [ 1, true ]

Any help would be appreciated.

Getting error as MIME type ('application/json') is not executable

I am getting error as this in console.

Refused to execute script from 'https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en&callback=jsonp_1500375938057_49602' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.

screen shot 2017-07-18 at 1 07 05 pm

Could you please let me know a solution ?

CORS FETCH on IE9

I use fetch-ie8 on an app based on react, and I apply CORS FETCH on this app, the fetch request always fails on IE9 ( the problem is 拒绝访问 Access denied ) , if I wanna insist on CORS FETCH, does it mean I have to use fetch-jsonp? Is there any better way?
p.s.
I've read your blog on camsong/blog#2 , great job!

Timeout error message

Hello,

The given URL is updated to include a '?' or '&' which is added so that the callback can be appended correctly. Upon errors, the reject(new Error(JSONP request to ${url} timed out)); will include the character that was added. This isn't a big deal but at first made me think a URL might be wrong because of the additional character. I think a quick fix to return an unmodified original URL during error messages would be beneficial.

Timeout callback error

Uncaught ReferenceError: jsonp_1503978517953_53960 is not defined

因为 timeout 后 function 被 reomve 导致返回后的函数执行出错

IE9 support

HI, I am trying to get the fetch-jsonp to work on IE9 without any success. Is there a way you can provide a working example please? I think promises are not supported by IE9 whihc makes this modules not work in IE9. can you provide a simple example please?

jsonp how to support post method

in my options, jsonp only supports get method via add script to implement cors
i am not sure if the description is right "The fetch-jsonp function supports any HTTP method. We'll focus on GET and POST example requests."

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.