function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Problem with authorization by SessionId

Hi to all!

I'm trying to run a simple visualforce page with JQuery Ajax request on it, to test how Apex Rest API is working. I am using current SessionId as a token, but I get a 401 Unauthorized Error. Can someone tell me what I am doing wrong?


Here is the code:


<apex:page >
<apex:includeScript value="{!$Resource.JQuery1_6}" />
<script type="text/javascript">
	var sessionId = 'OAuth {!$Api.Session_Id}';
	$(document).ready(function() {
		var url = "{!URLFOR('/services/data/v20.0/sobjects/Account')}";
			async: true,
			cache: false,			
            type: 'GET',
            url: url,       
            beforeSend: setHeader,
            success: function (result){
    function setHeader(xhr) {
        xhr.setRequestHeader('Authorization', sessionId);
        xhr.setRequestHeader('X-PrettyPrint', '1');



Sankalp JhingranSankalp Jhingran

Hi Denias,


I also tried the same code in VF page and got the same issue.

Here is the Error that I got in the JS-Console in chrome.


XMLHttpRequest cannot load Origin is not allowed by Access-Control-Allow-Origin.


I researched it and found that it is happening, due to the same origin policy, JavaScript running in Visualforce pages may not use XmlHttpRequest to directly invoke the REST API, since Visualforce pages have hostnames of the form, and the REST API endpoints are of the form

We can work around this restriction by using the AJAX Proxy. Since the AJAX proxy is present on all Visualforce hosts with an endpoint of the form, our Visualforce-hosted JavaScript can invoke it, passing the desired resource URL in an HTTP header.


You can find more info here:


Hope it is helpful.