I was reviewing lightning document, it seems the framework is currently limited to make callout only through apex, I understand this is done for security reasons, I feel its a big limitation while we compare with VF and other framework for adoption, it will also result in un-necessary server side code written and compatibility problem with existing projects like ForceTk, etc is a problem, Is there any plan to relax this restriction in future?
Asked
Active
Viewed 841 times
2 Answers
1
It's now possible to call external API using Javascript from within Salesforce Lightning.
Start by going to Setup → CSP Trusted Sites and adding your trusted site.
Which in this example is: https://api.postcodes.io/
Then use an approach like this:
({
postcodeSearch : function(component, postcode) {
var url = 'https://api.postcodes.io/postcodes/' + postcode;
this.makeAjaxRequest(component, url);
},
callAjax : function(method, url, async, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(component) {
if (xmlhttp.readyState == 4 ) {
callback.call(this, xmlhttp);
}
};
xmlhttp.open(method, url, async);
xmlhttp.send();
},
makeAjaxRequest : function(component, url) {
this.callAjax("GET", url, true,
function(xmlhttp){
if (xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
else if (xmlhttp.status == 400) {
console.log("makeAjaxRequest: 400 Error");
}else {
console.log("makeAjaxRequest: Error");
}
}
);
}
})
Robs
- 9,336
- 20
- 106
- 215
1
I feel the same pain as you do and asked already a similar question which is answered by Doug here
Lightning: is direct API access on the roadmap?
As to my knowledge this is still up to date and therefore not sure, if or when this constraint might be relaxed.
-
-
-
the performance reason given is vague though, since the client code executes on browser side. – realnumber Apr 01 '15 at 00:44
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://wwwcie.ups.com/rest/XAV. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).even with adding my site to CSP. – Tyler Zika Jul 15 '18 at 06:00Setup > CORS > New > Enter an orgin URL pattern– Robs Jul 31 '18 at 12:03