The Complete Guide to JSONP
JSONP, or JSON with Padding, is a technique used to load data from third-party servers while bypassing the same-origin policy. By default, web browsers restrict loading JSON files from domains and ports that are different from the current one. However, there are scenarios where you may need to retrieve data from another domain or access publicly available APIs served as JSON in your web application.
JSONP was developed before CORS (Cross-Origin Resource Sharing) came into existence. While CORS is considered the more appropriate approach to this problem, JSONP still has its use cases, and it’s important to be aware of it. It’s worth noting that since its inception, JSONP has had some security issues, so it’s crucial to understand the potential implications before using it.
Unlike CORS, JSONP only supports the GET HTTP method, making it less versatile. To use JSONP, the server must have JSONP support. For example, when using Express, you can utilize the Response.jsonp()
method, similar to Response.json()
, but specifically designed for JSONP callbacks. On the client side, you load the endpoint with a specified callback function.
Here’s an example using Express on the server side:
1 | res.jsonp({ username: 'Flavio' }) |
And the corresponding client-side code:
1 | <script src="http://localhost:2001/api.json?callback=theCallbackFunction"></script> |
The specified callback function should be a global function that will receive the JSON data:
1 | const theCallbackFunction = (data) => { |
Furthermore, jQuery simplifies the JSONP approach by abstracting it in its $.ajax()
method:
1 | $.ajax({ |
In summary, JSONP provides a way to load data from external servers by circumventing the same-origin policy. Although CORS is currently the preferred solution, understanding JSONP can be valuable in some scenarios. However, it’s important to be aware of the security implications associated with using JSONP.