top of page

Make HTTP Callout using Javascript in Lightning Web Components

To make an HTTP request in a Lightning web component (LWC) using JavaScript, you can use the fetch() API, which is a modern way to make HTTP requests.


Here is an example of how to make an HTTP GET request using fetch():




In this example, we are making a GET request to the URL https://sampleapi@api.com/posts.


Once the response is received, we convert it to JSON using the response.json() method, and then log the resulting data to the console using console.log(). If there is an error during the request, we catch it using the .catch() method and log the error to the console using console.error().


To make POST method callout use below code.





Note: Make sure to add the endpoint URL to the CORS whitelist of the Salesforce org if you are trying to access an external API from the LWC.


To add an endpoint URL to the CORS whitelist of a Salesforce org, you will need to do the following:

  1. Go to Setup in Salesforce.

  2. In the Quick Find box, type "CORS" and select "CORS" from the dropdown.

  3. Click "New" to create a new CORS rule.

  4. Enter the endpoint URL you want to add to the whitelist in the "Origin Domain" field.

  5. Select the HTTP methods that you want to allow for the endpoint URL.

  6. Click "Save" to save the new CORS rule.

Once you have saved the CORS rule, Salesforce will allow cross-origin requests from the specified endpoint URL.


Note: Make sure to specify the correct protocol (http or https) and domain name in the endpoint URL. Also, keep in mind that adding an endpoint URL to the CORS whitelist allows all Salesforce orgs to access that endpoint, so make sure to only add trusted and secure endpoints to the whitelist.

81 views0 comments

Comentários


bottom of page