How to Create a HTTP request in JavaScript, React, and Angular

How to Create a HTTP request in JavaScript, React, and Angular

As you know, HTTP is the main protocol used to structure the transmission of data across the internet, primarily between a web browser and a web server. An HTTP header is the part of the HTTP request or response that carries specific information about that request or response. For example, the header can be used to indicate a preferred media format. When you build a chat application with QuickBlox SDKs you can use header data to retrieve specific data and it’s also possible to set HTTP requests in different ways. QuickBlox is a cloud-based communication platform that provides APIs and SDKs to enable developers to integrate chat, video calling, and other communication functionality into their mobile and web applications. In this article we will show how to retrieve HTTP Headers in JavaScript using examples in pure JS, React, and Angular, when building with QuickBlox chat SDKs.

Getting HTTP Responses for the QuickBlox Server

HTTP requests or responses have headers with additional context and metadata. For example, the QuickBlox server uses the headers in a response to send information about the session expiration date. To get specific information from the server for a user list, for example, you must use the request header to send data with your valid session token to the server. Using a valid session token to inform the server about permissions or other user abilities is a common security practice.

By default, we have access to general headers (some of them are deprecated) as a result of requests to the server. They are:

Cache-Control

Content-Language

Content-Type

Expires

Last-Modified

Pragma

If you need to use custom headers, your server must use Access-Control-Expose-Headers to set access to custom headers. You can see the qb-token-expirationdate header, which contains the session expiration date because the QuickBlox server uses this param.

In the following, as an example, we will show how to get the session expiration date from the HTTP response header and how to use the session token for getting a file from the QuickBlox server.

JavaScript language tools

As you know, there are three different ways to make HTTP requests in JS:

  • Fetch API

  • XMLHttpRequest

  • Angular’s HttpClient

Fetch API is a tool that's built into most modern browsers on the window object (window.fetch) and gives us the ability to make HTTP requests easily using JavaScript promises.

XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh.

For both of them, you could use pure JavaScript, in React and Angular.

If you use Angular you can use HttpClient. The HttpClient module is a part of the Angular framework that lets you make HTTP requests and has an RxJS Observable-based API.

How to retrieve data from the QuickBlox server using a Request Header

Let’s see how to get information about the session expiration date from the QuickBlox Server. To get this information we must send to the server a valid access token (a long string constant).

Note: Read our Server API documentation about how to get a session token.

For example, if you use JS QuickBlox SDK you can get a token from the current session with call QB.service.getSession().token. In the text below our session token is a string 'f82baa0467604922be083'.

You need to send the session token value to the server using the server request header using parameter QB-Token.

Let’s make some examples of code for this using different JS stack technology.

Example using the fetch API

window.fetch(QbUrl , {
  headers : {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'QB-Token', 'f82baa0467604922be083',
  }
 }).then((response) => {
          const qbTokenExpirationDate =
          response.headers.get('qb-token-expirationdate');
          console.log(qbTokenExpirationDate)
          return response.json();
 }).then(data => {
         console.log('response data in json format');
          console.log(data)
});

Example using the XMLHttpRequest

const req = new XMLHttpRequest();

req.open('GET', QbUrl, false);

req.setRequestHeader('QB-Token', 'f82baa0467604922be083');

req.send(null);

const headers = req.getAllResponseHeaders();

console.log(headers.get('qb-token-expirationdate'));

Example using the HttpClient

In the Angular framework, we can use the well-known Observable-based object HttpClient module to make requests to the server. Usually, the HttpClient module is used as a part of the Angular component. Let’s make an example with the HttpClient module in Angular.

First, we need to import the HttpClient module.

import { HttpClient } from '@angular/common/http';

Then, using the constructor we need to inject the HttpClient into the component.

constructor(private http: HttpClient) { }

To make a response we will use the following code:

const headers = new HttpHeaders().set('QB-Token', 'f82baa0467604922be083');
this.http.get(QbUrl,{headers, observe: 'response', responseType:'json'})
    .subscribe(resp => {
       console.log(resp.headers.get('qb-token-expirationdate'));
       // And access the body directly
       console.log(resp.body);
  });

Getting a File from the QuickBlox Server

Now, we know how to request a server using a token, for the last part of this article we will look at how to get a file from the QuickBlox server.

Let's make the example using an auth token outside the header of the request.

Imagine we have a situation where we need to get message attachment data. We will need to execute a request to the server like this:

api.quickblox.com/blobs/832403bed65748df805.. f82baa0467604922be083

Use the code below to get the data:

window.fetch(QbImageUrl).then((response) => {
  console.log('response is');
  console.dir(response);
  if (response.ok)
  {
    console.log('image full path is ');
    console.log(response.url);
    const res = response.blob();
    return res;
  }
  else
  throw response;
}).then(data => {
        console.log('response data');
        console.log(data)
     // const bloburl = URL.createObjectURL(blob);
     // img.src = bloburl;
}).catch( (err)=>{
           console.log(err)
});

Conclusion

Depending on the framework you choose, there are three ways to get a server header response or to make a request to a server. They are XMLHttpRequest (pure JS), fetch API (pure JS and React) and HttpClient (Angular). Each of these supports synchronous and asynchronous communications. This article provides examples of using each when attempting to use the server's response header. You can choose any because code examples for solving one problem are similar to each other.

Join the QuickBlox Dev Discord Community ! Share ideas, learn about software, and get support.

For additional information please check out the resources below:

Pure JavaScript and all frameworks

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

React only

https://use-http.com/#/

https://github.com/ilyalesik/react-fetch-hook#readme

Angular only

https://angular.io/tutorial/toh-pt6

https://angular.io/guide/http#reading-the-full-response

https://angular.io/guide/http