2

How to bypass CORS (Cross-Origin Resource Sharing) issue using headers or json-p

Solution usin JSON-P

Contents

If the above method is not working or you have any restriction in modifying the .htaccess or apache configuration file, then another workaround is using JSON-P (JSON-with-padding). In this method, the client expects the data returned by the API in JSON-P format. This method, for me is a dirty hack, but it should work in most of the situations.

In the client side ajax call we can have following code:

On the server side the API will return in the JSON-P format. Below is an example in PHP:

You might have noticed json_processor in the echo statement. This is the javascript callback function which is returned along with the json encoded array. The returned json value to the browser will be similar to the one below:

Now in our client side, we need to define the callback javascript function json_processor(). This function will be called automatically once the browser gets the API response.

NOTE: The method of using JSON-P is not a workaround to access REST API of any websites for which you don’t have any control of. This implementation requires code modification on both client as well as server side. This method should be considered only if the CORS headers is not working.

Swaroop Shankar V

2 Comments

  1. You can also check the open source program [Bypass Cors](https://chrishham.github.io/BypassCors/) ,
    an installable Electron App (Windows/Mac/Linux), that lets you Bypass ALL CORS Restrictions permanently,
    by allowing you to set your own custom Headers (+Origin).

    It is specifically designed to work with Web Apps and its perfect for Real Time Scraping.

    Disclaimer: I am the author of the program.

    • Thanks, Christopher, your project looks interesting. Will give it a try

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.