How do I make an HTTP request in JavaScript?
To make an HTTP request in JavaScript, you can use the fetch()
function. Here is an example of how to use fetch()
to make a GET request to an API:
fetch('https://example.com/api/endpoint')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
In the code above, fetch()
makes a GET request to the specified URL, and then the response is parsed as JSON and logged to the console. If there is an error making the request or parsing the response, it will be caught and logged to the console.
Alternatively, you can use the XMLHttpRequest
object to make an HTTP request. Here is an example of how to use XMLHttpRequest
to make a GET request to an API:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/endpoint');
xhr.onload = () => console.log(xhr.responseText);
xhr.onerror = () => console.error(xhr.statusText);
xhr.send();
In this example, XMLHttpRequest
is used to create a new request object, and then the open()
method is used to specify the type of request (GET) and the URL to make the request. The onload
and onerror
event handlers are used to handle the response and any errors, respectively. Finally, the send()
method is used to send the request.