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:

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

And the corresponding client-side code:

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

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

Furthermore, jQuery simplifies the JSONP approach by abstracting it in its $.ajax() method:

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

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.