Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
JSONP was a technique to load data from third-party servers, bypassing the same-origin policy. While CORS is now the standard approach, understanding JSONP provides historical context and you may encounter it in legacy codebases.
The problem JSONP solved
By default you can’t load a JSON file from a domain and port that’s different from your current one. You might serve your app from localhost:8080, but the API is served from localhost:2001.
This is blocked for security reasons by the Same-Origin Policy.
How JSONP works
JSONP exploits the fact that <script> tags are not subject to the same-origin policy. A server with JSONP support returns JavaScript code instead of plain JSON:
res.jsonp({ username: 'Flavio' })
On the client side, you load the endpoint specifying a callback function:
<script src="http://localhost:2001/api.json?callback=handleData"></script>
The callback function must be global and will receive the JSON data:
const handleData = (data) => {
console.log(data)
}
The server wraps the JSON in a function call: handleData({ username: 'Flavio' }), which executes when the script loads.
Limitations of JSONP
- Only supports GET requests (no POST, PUT, DELETE)
- Security vulnerabilities (the server could execute arbitrary JavaScript)
- No proper error handling
- Requires server-side support
CORS is better
CORS (Cross-Origin Resource Sharing) replaced JSONP as the proper solution. CORS:
- Supports all HTTP methods
- Has proper error handling
- Is more secure
- Works with standard
fetch()and XMLHttpRequest
Use CORS for all new projects. JSONP is only relevant when working with legacy APIs that don’t support CORS.