The JSONP Guide

By

Learn how JSONP loads JSON from third-party servers to bypass the same-origin policy, using a callback function and supporting only GET, before CORS existed.

~~~

By default you can’t load a JSON file from a domain and port that’s not the current one, and use it in your application.

You might serve the app from localhost:8080, but the API is served by another Node.js application running on localhost:2001.

Or you might want to access some publicly available API served as JSON, in the browser.

This is a common need to consume APIs, but in the browser we’re limited as for security reasons, because of the Same-Origin Policy this behavior must be denied by default to prevent possible issues.

JSONP was born before CORS existed, and CORS is what you should use today. JSONP is a legacy technique, but you can still run into it when you consume an old third-party API that only supports it, so it’s worth knowing how it works. It also has known security issues, so read about the security implications of using JSONP before relying on it.

JSONP only supports the GET HTTP method, so it’s much less capable than CORS.

How does it work

A server must have support for JSONP, for example Express allows you to use the Response.jsonp() method, which is like Response.json() but handles JSONP callbacks:

res.jsonp({ username: 'Flavio' })

On the client side, you load the endpoint specifying a callback function:

<script src="http://localhost:2001/api.json?callback=theCallbackFunction"></script>

The callback function must be a global that will receive the JSON data:

const theCallbackFunction = (data) => {
  console.log(data)
}

jQuery had a handy way of simplifying this approach by abstracting JSONP in its ajax() method:

$.ajax({
  url: 'http://localhost:2001/api.json',
  dataType: 'jsonp',
  success: (data) => {
    console.log(data)
  }
})

If you control the server, don’t add JSONP support to it. Enable CORS and let clients call it with fetch().

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about js: