[SalesForce] Sending HTTP POST Through Lightning App

I'm trying to send an HTTP POST to a third party API in a lightning application but keep running into an error:

Uncaught SyntaxError: Unexpected identifier

The problem lines of code are in my helper class:

// This first line alone throws the error
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint('https://www.google.com');
req.setHeader('Host','www.google.com');
Http http = new Http();
HTTPResponse res = http.send(req); 

Any ideas how to make this work?

Best Answer

As we discussed, you cannot do an API Request from Lightning Component directly at the moment.You need to it via APEX controller by calling @AuraEnabled method to do the job for the LC.

So there's an example I did from the code you shared in the chat:

TestCmp.cmp

<aura:component controller="LightningContactController"> 
    <ui:button label="Post Comment" press="{!c.postChatterFeed}"/> 
</aura:component>

TestCmpController.js

({ 
    postChatterFeed : function(cmp, event, helper) { 
        helper.postChatterFeed(cmp, event, helper); 
    } 
})

TestCmphelper.js

({ 

    postChatterFeed : function(cmp, event, helper) { 
        var action = cmp.get("c.getPostToPusher"); 

        action.setCallback(this, function(response) { 
            var state = response.getState(); 
            if (state === "SUCCESS") { 
                alert("From server: " + response.getReturnValue()); 
            } 
            else { 
                alert("ERROR"); 
            } 
        }); 

        $A.enqueueAction(action); 
        } 
    })

Apex Controller:

public class LightningContactController { 
    @AuraEnabled 
    public static String getPostToPusher() { 
        HttpRequest req = new HttpRequest(); 
        req.setMethod('POST'); 
        req.setEndpoint('https://www.google.com'); 
        req.setHeader('Host','www.google.com'); 

        Http http = new Http(); 
        HTTPResponse res = http.send(req); 
        return 'Hello world'; 
    } 
}
Related Topic