1

I have a requirement where I need to call my custom written Apex REST api from java-script in visualforce page, But somehow I'm getting that CORS issue which says my request has been blocked due to following error:

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

I know now it shouldn't throw any kind of CORS issue, because as per summer 16 release CORS is supported by Apex REST service, refer below post: https://releasenotes.docs.salesforce.com/en-us/summer16/release-notes/rn_apex_rest_cors.htm

And I already added request origin url (which is VF) in the CORS settings, Setup >> CORS

Second weird thing is it always show me GET call in the dev console, although I'm making a POST call in the API, may be it because of any redirection behavior. Please find error screenshot from my dev console. enter image description here

Can anyone suggests what's gone wrong here.

1 Answer 1

2

CORS in Salesforce is all kinds of messed up... The standard REST API (services/data) works fine in most cases (you actually don't even need CORS).

However, when send a request to https://yourdomain.visualforce.com/services/apexrest/*, salesforce will 301 redirect you to https://yourdomain.salesforce.com/services/apexrest/*.

Unfortunately when it does this, it doesn't seem to preserve the http method (POST in this case) and always redirects to GET.

You can solve this by instead just sending your requests directly to https://yourdomain.salesforce.com/ in the first place. You will of course, need a CORS whitelist for https://yourdomain.visualforce.com.

TIP: You can get the standard URL of your ORG in visualforce like this:

 <script type="text/javascript">    
      const restHost = '{!URLFOR("/", null)}';
      const accessToken = '{!$Api.Session_ID}';
 </script>
1
  • 1
    Thanks! it will help someone else here. May 25, 2019 at 7:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .