Network Requests in JavaScript

One of the crucial and fundamental component of a website is to make Network Requests to fetch some data. There are a lot of libraries available now, like axios, that make this task very easy to implement for the developers. But, if you've ever wondered what goes on underneath those libraries or if you want to achieve this using pure JavaScript, keep reading.

XMLHttpRequest (XHR)

The XHR instances are used to interact with servers in JavaScript. Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML!

To create an XHR object, simply call the constructor:

const xhr = new XMLHttpRequest();

Methods

open()

This method only initialises the created XHR object, doesn't send the request to the server. It accepts the following arguments:

  • method: string: The HTTP method, e.g., GET, POST, PUT, etc.

  • url: string: The URL to fetch the data from.

  • async?: boolean: Specify if the request should be sent asynchronously. true by default as calling an API synchronously will block the JS thread and jam any user interactions and hence is not recommended!

  • user?: string | null: The username for authentication.

  • password?: string | null: The password for authentication.

const url = 'https://tinyfrontend.com/xhr-test';
xhr.open('GET', url, true);

send(body?: any)

This is the method that actually sends the request to the server and:

  • Returns immediately if the async flag is true.

  • Blocks and returns when the request finishes if the async flag is false.

The body argument is passed if the method supports it, otherwise discarded.

setRequestHeader()

Used to set request headers like Content-Type, Cookie, etc.

xhr.setRequestHeader('Content-Type','text/html');
xhr.setRequestHeader('Authorisation','*****');

abort()

Used to abort an ongoing request.

getResponseHeader(name: string)

Used to get a particular header from the response like Cookie, etc. If you want all the headers in a single string, use getAllResponseHeaders().


Subscribe to read the full content