What is an HTTP Request?
HTTP (Hypertext Transfer Protocol) is a protocol used by web browsers and servers to communicate with each other. HTTP requests are messages sent by the client (usually a web browser) to the server, asking for a resource (such as a web page or a file) to be sent back. HTTP requests typically include a method (such as GET or POST), a URL, and some additional headers.
In the code above, we first create a new instance of the XMLHttpRequest object using the
new XMLHttpRequest() syntax. We then call the
open() method to specify the HTTP method (in this case, GET) and the URL to request.
We then define a callback function to be called when the request is complete (
xhr.onload). In this function, we first check if the status code of the response is 200 (which means the request was successful). If it was, we log the response text to the console.
Finally, we call the
send() method to send the HTTP request.
In the code above, we call the
fetch() function with the URL to request as its argument. This returns a Promise that resolves the response from the server. We then call the
json() method on the response object to parse the response data as JSON. Finally, we log the parsed data to the console.
The Fetch API is more concise and easier to use than XMLHttpRequest, and it also has better support for Promises and async/awaits.