Tuesday, October 8, 2019

Lightning Component Web Service Integration

When calling web service from lightning component, we can either call it from apex using @AuraEnabled method, or we can call from lightning component client side controller. This is specially important when you want to avoid governor limits on Apex side, e.g. uploading file bigger than 7MB or calling web service which could potentially take more than 120s. We can directly use browser to call the web service.

Calling web service from client side controller (browser integration)



1) We need to make sure that web service we call, allows cross origin and it is https enabled

We wrote simple web service in Heroku
https://basic-authentication-ws.herokuapp.com/echo




2) We need to make sure the web service URL is added to CSP trusted site for locker service

https://basic-authentication-ws.herokuapp.com




3) Now, lightning component (client side controller)

We can make call to web service


({
    doInit: function (c, e, h) {
    },
    postData: function (c, e, h) {
        c.set('v.isProcessing', true);
        var xhr = new XMLHttpRequest();
        var url = 'https://basic-authentication-ws.herokuapp.com/echo';
        xhr.open('POST', url, true);
        xhr.onload = function () {
            if (this.status === 200) {
                c.set('v.isProcessing', false);
                c.set('v.response', this.response);
            }
        };

        xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
        xhr.send(JSON.stringify({message: c.get('v.message')}));
    }
});


Source Code

Heroku
https://github.com/c-shah/basic-authentication

Salesforce
https://github.com/springsoa/springsoa-salesforce/tree/master/aura/webserviceTest

No comments: