0

I am trying to fire a platform event directly from lightning Web component without using Apex. I choosen the route to call API from JavaScript in Lightning Web component.

My code looks like:-

import { LightningElement } from 'lwc';
const QUERY_URL = 'https://lextraining-dev-ed.my.salesforce.com/services/data/v48.0/sobjects/Low_Ink__e/';
export default class Batch extends LightningElement {
    searchKey;
    handleSearchKeyChange(event) {
        this.searchKey = event.target.value;
    }
    handleSearchClick() {
        let user = {
            "Printer_Model__c" : this.searchKey
        };          

        fetch(QUERY_URL, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json;charset=utf-8'
            },
            body: JSON.stringify(user)
        });
    }
}

I have added the remote site setting and CORS in my Org.

enter image description here


enter image description here

Problem :

I am getting below error while making the call.

Access to fetch at 'https://lextraining-dev-ed.my.salesforce.com/services/data/v48.0/sobjects/Low_Ink__e/' from origin 'https://lextraining-dev-ed.lightning.force.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

enter image description here

In the docs, it says Use Lightning Data Service (LDS) to work with data and metadata for Salesforce records. Lightning Data Service is built on top of the public User Interface API, but it only supports a subset of the API. That subset covers many of the typical use cases for working with data. You can’t make calls to Salesforce APIs other than LDS from JavaScript code.

If LDS doesn’t support the object you are looking to use, or if you want to use another Salesforce API, write an Apex class.

So, Does it mean, i must use Apex or is there any alternative available to achieve it?

3

To receive and publish events, use the lightning-emp-api module. It provides all the methods you need to work with Platform Events. Here's the example code included from the documentation:

import { LightningElement } from 'lwc';
import { subscribe, unsubscribe, onError, setDebugFlag, isEmpEnabled } from 'lightning/empApi';

export default class EmpApiLWC extends LightningElement {
    channelName = '/event/Test__e';
    isSubscribeDisabled = false;
    isUnsubscribeDisabled = !this.isSubscribeDisabled;

    subscription = {};

    // Tracks changes to channelName text field
    handleChannelName(event) {
        this.channelName = event.target.value;
    }

    // Initializes the component
    connectedCallback() {       
        // Register error listener       
        this.registerErrorListener();      
    }

    // Handles subscribe button click
    handleSubscribe() {
        // Callback invoked whenever a new event message is received
        const messageCallback = function(response) {
            console.log('New message received: ', JSON.stringify(response));
            // Response contains the payload of the new message received
        };

        // Invoke subscribe method of empApi. Pass reference to messageCallback
        subscribe(this.channelName, -1, messageCallback).then(response => {
            // Response contains the subscription information on subscribe call
            console.log('Subscription request sent to: ', JSON.stringify(response.channel));
            this.subscription = response;
            this.toggleSubscribeButton(true);
        });
    }

    // Handles unsubscribe button click
    handleUnsubscribe() {
        this.toggleSubscribeButton(false);

        // Invoke unsubscribe method of empApi
        unsubscribe(this.subscription, response => {
            console.log('unsubscribe() response: ', JSON.stringify(response));
            // Response is true for successful unsubscribe
        });
    }

    toggleSubscribeButton(enableSubscribe) {
        this.isSubscribeDisabled = enableSubscribe;
        this.isUnsubscribeDisabled = !enableSubscribe;
    }

    registerErrorListener() {
        // Invoke onError empApi method
        onError(error => {
            console.log('Received error from server: ', JSON.stringify(error));
            // Error contains the server-side error
        });
    }
}
2
  • Thanks @sfdcfox, Do you have any thought on rest API route? Should i consider that is not possible currently with Lightning Web Component? Jul 5 '20 at 5:26
  • @sanketkumar the main REST API is blocked in Lightning, which is a security feature. You're allowed to use the limited API (e.g. UI-API) instead, and Apex. So, your only two options are lightning-emp-api or Apex.
    – sfdcfox
    Jul 5 '20 at 14:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.