1

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?

realnumber
  • 1,623
  • 14
  • 27

2 Answers2

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
    this doesn't work for me. I still get 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:00
  • @TylerZika the error message says you are missing CORS which can be set via Setup > CORS > New > Enter an orgin URL pattern – Robs Jul 31 '18 at 12:03
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.

Uwe Heim
  • 28,350
  • 18
  • 115
  • 283