To fetch data from an API in JavaScript, you can use the fetch()
function or the XMLHttpRequest (XHR) object.
Here's an example of using fetch()
:
index.tsx151 chars5 lines
This code sends a GET request to https://example.com/api/data
, parses the received JSON data, and logs it to the console. It also catches any error that might occur during the operation.
Here's an example of using XHR:
index.tsx265 chars10 lines
This code creates an XHR object, sets a callback function to be called when the response is ready, and sends a GET request to https://example.com/api/data
. When the response is received, the callback function parses the JSON data and logs it to the console.
Both fetch()
and XHR are asynchronous functions, meaning that they don't block the main thread while waiting for the response. Asynchronous programming is essential in web development, especially when dealing with APIs, as it allows the UI to remain responsive while the data is being fetched.
gistlibby LogSnag