[SalesForce] Invoke Rest Service from Visualforce page

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>

Best Answer

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>
Related Topic