Fetching JSONP data with JavaScript

Some APIs choose JSONP over CORS to respond to cross-domain requests.

JSONP allows the caller to provide a client side JavaScript callback to execute once data is fetched. If you try to use the standard fetch API to request data from a JSONP endpoint, it will most likely fail due to invalid server CORS configuration.

Most APIs use CORS instead of JSONP for many reasons covered here.

For the remaining that still use JSONP, fetch-jsonp provides a similar api to fetch that includes Promise support.

If you use SWR to request data for your components, you could use fetch-jsonp instead of fetch for your fetcher function.

A sample component that fetches data from a JSONP endpoint.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store