HTTP Request in JavaScript
HTTP Request in JavaScript
Using XMLHttpRequest:
javascript
Copy code
xhr.send();
In this example, we create a new XMLHttpRequest object, open a GET request to the specified URL
response. When the ready state changes to 4 (indicating that the response has been received) and
the status is 200 (indicating a successful response), we can process the response.
javascript
Copy code
console.log(error); });
With the fetch API, we directly call the fetch function with the URL. It returns a Promise that resolves
to the Response object. We can then use the ok property of the response to check if the request was
successful. If so, we can call the json() method on the response to parse the response data. Finally,
we can process the data in the second .then() block or handle any errors in the .catch() block.
Both methods can be used to make different types of requests (GET, POST, etc.), and you can set
request headers, send data in the request body, and handle other aspects of the HTTP
request/response cycle.