HOW DO I MAKE AN HTTP REQUEST IN JAVASCRIPT?
In JavaScript, you can make an HTTP request using the XMLHttpRequest object or the newer fetch API. I'll provide examples for both methods:
- Using XMLHttpRequest:
In this example, we create a new XMLHttpRequest object, open a GET request to the specified URL (https://api.example.com/data), and set the onreadystatechange event handler to handle the response. Once the request is completed (readyState 4) and the status is successful (status 200), we parse the response using JSON.parse() and process it accordingly.
- Using the fetch API:
In this example, we use the fetch() function to make a GET request to the specified URL. We chain the then() method to handle the response. If the response is successful (response.ok), we parse the JSON data using response.json(). If there is an error, we throw an error with the corresponding status. Finally, we handle the data in the second then() callback and catch any errors using the catch() method.
These examples demonstrate the basic usage of making an HTTP request in JavaScript. You can modify them to suit your specific needs, such as making POST requests or including request headers.


Comments
Post a Comment