Background

Under the same-origin policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin.

There are basically two methods to visit cross-origin resources.

The first one and preferred one is called CORS (cross-origin HTTP request).

The second one and obsolete one is called JSONP.

CORS

CORS just uses the normal procedure of XMLHttpRequest, but relies on a HTTP header called Access-Control-Allow-Origin of the response by the target site.

For example, if the field is Access-Control-Allow-Origin: example.com, requests from example.com can access the resources in the target site.

For details, please refer to MDN.

JSONP

JSONP allows a page to receive JSON data from a different domain by adding a <script> element to the page which loads a JSON response with a callback from different domain.

This is kind of a dirty hack. I think it’s better to use CORS when possible.

What if the origin and target site are using different protocols

For example, if the origin site is using https and the target site only supports http, is there a method to bypass the restriction?

Unfortunately, no. We have to make sure they’re using the same protocol.

A note on the same-origin policy

Leave a Reply

Your email address will not be published. Required fields are marked *