To make API calls in JavaScript, you can use the fetch
function or libraries like axios
or jQuery.ajax
. Here’s an example using the fetch
function:
fetch('https://api.example.com/data') .then(response => response.json()) .then(data => { // Process the received data here console.log(data); }) .catch(error => { // Handle any errors that occurred during the API call console.error(error); });
In this example, we are making a GET request to the URL https://api.example.com/data
. The fetch
function returns a Promise that resolves to the response from the API. We can then use the json
method on the response object to parse the response data as JSON.
Once we have the parsed data, we can process it as needed. In this example, we are simply logging the data to the console.
If any errors occur during the API call, the catch
block will handle them and log the error to the console.
Note: To use this code in an HTML file, you can include it within a <script>
tag. For example:
<!DOCTYPE html> <html> <head> <title>API Call Example</title> </head> <body> <script> // Place the API call code here </script> </body> </html>
Remember to replace 'https://api.example.com/data'
with the actual API endpoint you want to call.