To make an HTTP request and get data in JavaScript, the Fetch API can be used. It provides a simple interface for fetching resources asynchronously across the network.
Here's an example of how to make a GET request using the Fetch API:
index.tsx123 chars5 lines
In the above code, the fetch
function takes the URL of the resource you want to fetch as its argument. It returns a Promise that resolves to the Response object representing the response to the request.
The then
method is chained onto the Promise returned by the fetch
function. It takes a callback function that will be called once the request is successfully completed. In this callback function, the json
method is used to extract the JSON data from the response object.
If there is an error during the request or parsing the response data, the catch
method will be called with the error object.
Alternatively, you can use async/await
with fetch to simplify the code and handle errors more elegantly:
index.tsx207 chars12 lines
In the above code, the getData
function is declared as async
. It uses the await
keyword to wait for the fetch request to complete and the JSON data to be parsed. If there are any errors, they are caught by the try/catch
block.
gistlibby LogSnag