In this blog, I am going to explain how to solve CORS in Salesforce by using JSONP( JSON Padding )
What is CORS?
CORS introduces a standard mechanism that can be used by all browsers for implementing cross-domain requests. The spec defines a set of headers that allow the browser and server to communicate about which requests are (and are not) allowed.Cross-Origin Resource Sharing (CORS) allows us to use Web applications within browsers when domains aren’t the same. For example, a site with domain wants to execute x.org AJAX requests to a Web application with the domain y.org using HTTP.
For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and Fetch follow the same-origin policy. So, a web application using or XMLHttpRequest Fetch could only make HTTP requests to its own domain.
The Cross-Origin Resource Sharing standard works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. Additionally, for HTTP request methods that can cause side-effects on server’s data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers “preflight” the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon “approval” from the server, sending the actual request with the actual HTTP request method. Servers can also notify clients whether “credentials” (including Cookies and HTTP Authentication data) should be sent with requests.
What is JSONP?
For Examples in this script, parseResponse is the function which will return as part of the script invocation
script isn’t subject to the browser’s same-origin policy, the response will simply be executed in the browser with our parseResponse function.
Breaking it all down
The core elements of JSONP, then, are as such:
- A callback function defined on your site.
- A request to the remote API via
- Includes a special param providing the name of your callback function
- The response:
- That consists of:
- A function call, the name of which you specified in the request
- With the argument being the JSON data of interest
- Gets executed immediately, as if it were called from your own domain
Let’s test now:-
Create a visualforce page with the following code.
Now after loading the page, go to console you will see an error message as shown below.
Now Replace the above code with the below code which is having JSONP logic
Now if you can go and see the console, you will not see any error message.