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:includeScript value="//code.jquery.com/jquery-1.11.1.min.js" />
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()}';

        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);
    <!--call javaScript-->
    <input type="button" value="Call API" onclick="apiCall()" />
    <div id="apiData">
  • 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


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 >
var s = '{!GETSESSIONID()}';
    var x = new XMLHttpRequest();
    x.setRequestHeader('Authorization','Bearer '+s);
    x.onload = function() { alert(this.response); }
  • 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 .