[SalesForce] How to open up a public REST API to JavaScript in any website

I have set up a public Salesforce REST api as explained in this post. (i.e. I have set up a site that directs a user to the webservice and have given the public site user access to only those records that are absolutely required as well as the Apex class that defines the web service). I am using a developer org and my intent was just to set up a REST web service that I could use while playing around with the Backbone.js library.

If I post the endpoint etc into my browser address bar then I get a nice bit of json back from the api:

https://mydomain-developer-edition.eu0.force.com/services/apexrest/mymethod.json

However, when Backbone.js issues an ajax call, then I get the following error:

'Access-Control-Allow-Origin' header is present on the requested
resource.

which, according to this post is because I am using https but the browser has detected that the target domain is different from the current domain, which is apparently called a cross-domain reference.

Fair enough, but:

  • I can't see an option to use a non-secure http endpoint. Maybe it is because I am using a developer edition org, but in the sites configuration that I have, there doesn't seem to be an option to add another custom url if that would help. Is there a way to configure a non-secure http endpoint?
  • If all of salesforce's REST endpoints have to use https, then I would have thought that there would be a lot more people having issues trying use javascript libraries such as Backbone.js, but I can't see anyone having asked this before on this site. Is there a best-practice way I could be doing this without running into the cross-domain referencing problem?

Thanks a lot

Best Answer

You can actually set the Access-Control-Allow-Origin header in your web service to make this work:

RestContext.response.addHeader('Access-Control-Allow-Origin', 'http://foo.example.com');

Just substitute your site's domain for http://foo.example.com, or read HTTP access control (CORS) to learn more about wildcards if you want to open the doors wider.

Related Topic