You need to sign in to do that
Don't have an account?

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')}"; $.ajax({ async: true, cache: false, type: 'GET', url: url, beforeSend: setHeader, success: function (result){ console.log(result); } }); }); function setHeader(xhr) { xhr.setRequestHeader('Authorization', sessionId); xhr.setRequestHeader('X-PrettyPrint', '1'); } </script> </apex:page>
Thanks,
Denias
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 https://na3.salesforce.com/services/data/v20.0/sobjects/Account. Origin https://myp1.na3.visual.force.com 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 abc.na1.visual.force.com, and the REST API endpoints are of the form na1.salesforce.com.
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 https://abc.na1.visual.force.com/services/proxy, our Visualforce-hosted JavaScript can invoke it, passing the desired resource URL in an HTTP header.
You can find more info here:
https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit
http://www.salesforce.com/us/developer/docs/ajax/Content/sforce_api_ajax_queryresultiterator.htm#ajax_proxy
Hope it is helpful.
Regards,
Sankalp
Blog: forcesecrets.blogspot.com