[SalesForce] CORS whitelisting not working as expected

I'm having an issue with CORS where I'm unable to make a POST request to a Salesforce site from another site, but one I have listed in my CORS whitelist. Not sure if I have something set up wrong, or if there's just something I'm not understanding about CORS.

So the scenario I have is I have a jQuery ajax call like this:

$.ajax({
    url: "https://sf-site-here.na34.force.com/pageName",
    type: "POST",
    dataType: "json",
    ...
});

From, say, external.site.com. I've added https://external.site.com to my CORS whitelist, but when I try to make the POST (which is for a jQuery autocomplete, just for a little bit more context) I still get

XMLHttpRequest cannot load https://sf-site-here.na34.force.com/pageName. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://external.site.com' is therefore not allowed access.

The page I'm trying to access is a VF page that returns a json string. It's a VF page with contentType="application/x-JavaScript; charset=utf-8". I'm trying to access the page via sites.

Am I misunderstanding what that whitelist applies to? Does it only work for certain calls, or is there something else I need to set up on the site?

Best Answer

Ok. I did some research on this and looks like we both interpreted the Salesforce CORS documentation wrongly.

Salesforce CORS says that CORS is only for making requests to Supported Salesforce APIs, Apex REST, and Lightning Out but not for making calls to Salesforce pages(as you are trying to do) because that is not exposed an API.

I created a simple jsfiddle to prove this further and my understanding is correct.

  1. Created a simple public REST API on my developer edition org as explained in this link.
  2. Whitelisted jsfiddle in my org under CORS.

If I make calls from jsfiddle, a request goes through fine and response is returned.

If I undo the whitelisting of jsfiddle in my org, the request fails(with the same error message as you are getting) proving that CORS is needed for the request to work.

I think for your case, you need to create a REST API and make calls to it by whitelisting the calling page.