0

I have a VF page that tries to invoke REST API from within script. On button click I am getting error: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I am specifically trying to invoke rest api from clientside. Is there way to fix this issue or any alternate option to invoke rest service from clientside?

Below is my page code:

<apex:page>
<apex:includeScript value="//code.jquery.com/jquery-1.11.1.min.js" />
<script>
function apiCall() {
    //Get a reference to jQuery that we can work with
    $j = jQuery.noConflict();
    //endpoint URL
    var weblink = "https://crmslightning-dev-ed.my.salesforce.com/services/apexrest/v1/restResourceTest"; 

    var access_token = '{!GETSESSIONID()}';

    $j.ajax({
        url: weblink,
        type: 'GET', //Type POST or GET
        dataType: 'json',
        beforeSend: function(request) {
            //Add all API Headers here if any

            request.setRequestHeader('Authorization', 'Bearer ' + access_token);
            request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
            request.setRequestHeader('Access-Control-Allow-Origin', "*");
            request.setRequestHeader('Access-Control-Allow-Methods', "GET,POST");
        },

        crossDomain: true,
        //If Successfully executed 
        success: function(result) {

            console.log('Response Result' + result);

        },

        //If any Error occured
        error: function(jqXHR, textStatus, errorThrown) {
            //alert('ErrorThrown: ' + errorThrown);
        }
    });
}
</script>
<apex:form>
    <!--call javaScript-->
    <input type="button" value="Call API" onclick="apiCall()" />
    <div id="apiData">
    </div>
</apex:form>
</apex:page>
1
  • what is the purpose of invoking REST from page/javascript? You can do that from controller Aug 20, 2018 at 18:45

1 Answer 1

0

All of the APIs are available on the visualforce.com domain, so you can access them without a cross-domain request. Do not include the server URL. You should use the domain that you are on.

var weblink = "/services/apexrest/v1/restResourceTest"; 

Your browser will understand this as an attempt to use the current host name, which will work. Here's a copy-paste example for you that works:

<apex:page >
    <script>
var s = '{!GETSESSIONID()}';
    var x = new XMLHttpRequest();
    x.open('GET','/services/data');
    x.setRequestHeader('Authorization','Bearer '+s);
    x.onload = function() { alert(this.response); }
    x.send(null);
    </script>
</apex:page>
2
  • this still gives me same error. Also I have mydomain enabled if that may create an issue.
    – Shrey
    Aug 20, 2018 at 19:35
  • @Shrey I'm using my domain in a developer edition org.
    – sfdcfox
    Aug 20, 2018 at 19:36

You must log in to answer this question.

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