Find your content:

Search form

You are here

How do I open up a public REST API to JavaScript in any website?

 
Share

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


Attribution to: Joe

Possible Suggestion/Solution #1

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.


Attribution to: metadaddy

Possible Suggestion/Solution #2

The issue is not really http or https - unless the data is very innocuous https is the best choice - but the security feature of your browser that ensures a web page isn't making requests to an unexpected server.

One way to avoid this problem is to serve your Backbone based app from the same Salesforce Site that your REST API is served from: same domain means no problem.

AFAIK solutions like JSONP are not available. But I would be happy to be wrong about that and interested in any other solutions too.


Attribution to: Keith C
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/34379

My Block Status

My Block Content