Making a Network Request with Asynchronous JavaScript
Tags: webdev, javascript, beginners, tutorial
Published: 2023-03-14 12:52:30

A network request is a message sent from one computer or device to another over a network, such as the internet. It typically involves a client making a request for data or resources from a server, and the server responding with the requested information.

For example, when you visit a website in your web browser, your browser sends a network request to the website's server, asking for the webpage to be delivered to your computer. The server then responds with the webpage data, which is displayed in your browser.

Asynchronous JavaScript is a powerful feature that allows you to make network requests without blocking the main thread of your application. 

When making a network request, JavaScript can be executed asynchronously so that the user can continue to interact with the web application while the request is being processed in the background.

Making a network request with Asynchronous JavaScript can be done using the [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) (XHR) object or the newer [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)

##Fetch API
To make a network request with the Fetch API, you can use the fetch() function which returns a [Promise](https://dev.to/mattryanmtl/what-is-a-promise-callback-7ke) that resolves to the Response object representing the response to your request. 

Here's a basic example:

```js
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
```
In this example, we are making a GET request to the URL https://api.example.com/data and then calling the [json()](https://developer.mozilla.org/en-US/docs/Web/API/Response/json) method on the Response object to parse the response data as JSON. We then log the parsed data to the console. Finally, we catch any errors that might occur during the request or parsing process.

You can also pass in additional options to the [fetch()](https://developer.mozilla.org/en-US/docs/Web/API/fetch) function, such as specifying the HTTP method, headers, and request body. 

Here's an example that sends a POST request with JSON data in the request body:

```js
fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ name: 'John Doe', age: 30 })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
```
In this example, we are specifying the method option as 'POST' and the headers option to set the [Content-Type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) header to 'application/json'. We are also passing in a JSON object as the request body by calling the [JSON.stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) method on the object.

##XMLHttpRequest

To make a network request with XMLHttpRequest (XHR), you can create a new instance of the XMLHttpRequest object and then use its methods to configure and send the request. 

Here's a basic example:
```js
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onload = function() {
  if (xhr.status === 200) {
    const data = JSON.parse(xhr.responseText);
    console.log(data);
  } else {
    console.error('Request failed. Status code:', xhr.status);
  }
};
xhr.onerror = function() {
  console.error('Request failed. Network error.');
};
xhr.send();
```
In this example, we create a new instance of the XMLHttpRequest object and call its [open()](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open) method to configure the request method and URL. We then set up event listeners for the load and error events, which will be triggered when the response is received or if there is a network error.

Inside the load event listener, we check the status property of the XHR object to see if the response was successful (status code 200). If it was successful, we parse the response data as JSON using the [JSON.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) method and log it to the console. If it was not successful, we log an error message with the status code.

Inside the error event listener, we log an error message indicating that there was a network error.

You can also use the XHR object's [setRequestHeader()](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader) method to set custom headers, and its send() method to send data in the request body. 

Here's an example that sends a POST request with JSON data in the request body:

```js
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/data');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
  if (xhr.status === 200) {
    const data = JSON.parse(xhr.responseText);
    console.log(data);
  } else {
    console.error('Request failed. Status code:', xhr.status);
  }
};
xhr.onerror = function() {
  console.error('Request failed. Network error.');
};
xhr.send(JSON.stringify({ name: 'John Doe', age: 30 }));
```
In this example, we call the setRequestHeader() method to set the Content-Type header to 'application/json', and then pass in a JSON object as the request body by calling the JSON.stringify() method on the object. We then call the [send()](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send) method to send the request.

##Conclusion
Asynchronous JavaScript is a powerful feature that allows you to make network requests without blocking the main thread of your application. The Fetch API and XMLHttpRequest object are two ways to make network requests with asynchronous JavaScript. 

While the Fetch API is newer and provides a simpler and more concise API, the XMLHttpRequest object is still widely used and supported by all modern web browsers.