JSONP
Most browsers enforce same origin policy on some resources. In order to make the request to cross origin resource, you can set CORS on the resource.
Alternatively, you can use JSONP which stands for JSON with Padding to tackle the problem.
Usage is as easy as below:
In html, request the resource with script tag (script is not restricted by the same origin rule, <img> <iframe> are also other examples)
<script src="https://resource.com?callback=foo"></script>
The server should provide the JSONP implementation. The above request should return response like:
foo({data:'\I am the data returned\'}) (escaping quotes is necessary)
Basically, it’s returning a JavaScript snippet. foo is the function which is already defined in the global scope. Together the actual data: {data: 'I am the data returned'} is passed to the function.
Seems nice, then why do we bother using CORS?
Because
- JSONP does not have decent error handling. No HTTP status code to identify the error
- Relying on server to provide JSONP implementation
- Security issues (without CORS, this resource is accessible by everyone)
