by Anthony Ng
How to use JSON padding (and other options) to bypass the Same Origin Policy
In this article, we will be looking at what JSONP is, its drawbacks, and some alternatives to JSONP.
You may have run into situations where you make an API call from one origin to another. For example, we have a page served from localhost:3000 that is calling an API from localhost:8000.
Note: We will refer to localhost:3000 as our client server. We will refer to localhost:8000 as our API server.
But we see this intimidating error.
This is the Same-Origin Policy protecting us. This policy restricts how resources from one origin interact with resources from another origin. It is a critical security mechanism in the browser. But there are instances where we want to make cross-origin requests to trusted resources.
JSONP (JSON with Padding) provides a work-around for this Same-Origin Policy problem. Let’s look at how JSONP came to be.
Most servers allow you to set the content type. In Express, you would do:
<script> tag can reference a URL that doesn’t h
ave a js extension.
Script tags are not limited by the Same-Origin Policy. There are other tags, such as
You can pass arguments as you would for a normal function call.
This is what JSONP is. Instead of using
XMLHttpRequest to make an API call to retrieve data, we used a
<script> tag. Because we u
sed a <script> tag, we were able to bypass the Same-Origin Policy.
Most servers allow you to specify the name of your padding function.
The server takes your padding function name as a query. It invokes your padding function with the JSON data as an argument.
I have not thought of a reason to do this.
Alternatives to using JSONP
There is no official spec for JSONP. I think of JSONP as more of a hack.
<script> tags can only make GET requests. So JSONP can only make GET requests.
Cross-Origin Resource Sharing has an official specification, and is the preferred way of getting around the Same-Origin Policy.
You can enable Cross-Origin Resource Sharing by adding a header to our Response.
This means all origins can use this resource without fear of the Same-Origin Policy.
Sometimes, you don’t have control over the server-code though. You would not be able to include the
Access-Control-Allow-Origin header. An alternate solution is to make your own proxy server make the cross-origin request for you. The Same-Origin policy only applies to the browser. Servers are free to make cross-origin requests.
Questions? Comments? Please leave a message below.