v0.9

HTTPClientFetch

class HTTPClientFetch → file: core/lib/HTTPClientFetch.js

The HTTPClientFetch has almost same methods as HTTPClient class.
This HTTP client is based on fetch(). See more

Instance

Instance created with new HTTPClientFetch(opts)

Properties

Property Description Type Default
opts options (see the table below) object
url requested URL, for example: https://jsonplaceholder.typicode.com/todos?page=22 string
protocol HTTP protocol string http:
hostname server, host name string
port HTTP port number number 80
pathname path name string /
queryString query string, for example ?page=22 string
timeout time in ms for waiting the response; set from opts.timeout number 8000
responseType the XHR response type: 'text', 'json', 'blob', 'arraybuffer' (read more); set from opts.responseType string 'text'
req_headers defined request headers; set from opts.headers object {}
interceptor A function to be executed before each request is sent. It's defined by the setInterceptor(). Function null

opts

Property Description Type Default
encodeURI to encode URI, for example ?x=jen dva → ?x=jen%20dva boolean false
timeout the request timeout, if 0 or false it will never timeout number 8000
responseType the XHR response type: 'text', 'json', 'blob', 'arraybuffer'. Use 'blob' for file download (see more) string 'text'
retry the number of retries number 3
retryDelay the delay between retries in ms number 5500
maxRedirects the max number of 301 redirects to follow number 3
headers request headers object {authorization: '', accept: '*/*'}
this.opts = {
  encodeURI: false,
  timeout: 8000,
  responseType: '', // 'text', 'json', 'blob', 'arraybuffer'. Use 'blob' for file download (https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType)
  retry: 3,
  retryDelay: 5500,
  maxRedirects: 3,
  headers: {
    authorization: '',
    accept: '*/*' // 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
  }
};

Methods

async askOnce(url, method, bodyPayload) :Promise<answer>

Sending one HTTP request to HTTP server. The returned value is the Promise with answer object.
- 301 redirections are not handled.
- retries are not handled
    ARGUMENTS:
  • url :string - requested URL
  • method :string - GET, POST, PUT, DELETE, ...
  • bodyPayload :any - body payload for POST, PUT, ...

async ask(url, method, bodyPayload) :Promise<Array<answer>>

The ask method is designed to send an HTTP request to a server, handling potential redirections (3xx status codes) and retries in case of timeouts (status code 408). It ensures robust and reliable communication by retrying failed requests and following redirects up to a specified limit.
- 301 redirections are handled.
- retries are handled
Returns a promise that resolves to an array of answer objects. Each answer object contains details about the request and response, including status codes, headers, and content.
    ARGUMENTS:
  • url :string - requested URL
  • method :string - GET, POST, PUT, DELETE, ...
  • bodyPayload :any - body payload for POST, PUT, ...

async askJSON(url, method, body) :Promise<answer>

Fetch the JSON from API response. Redirections and retries are not handled. The returned value is the Promise with answer object.
    ARGUMENTS:
  • url :string - requested URL
  • method :string - GET, POST, PUT, DELETE, ...
  • body :string|object - http body as Object or String JSON type

async askHTML(url) :Promise<answer>

Get the HTML file content. Redirections and retries are not handled. The returned value is the Promise with answer object.
    ARGUMENTS:
  • url :string - requested URL, for example /assets/product.html

async askJS(url) :Promise<answer>

Fetch the content of the JS file. Redirections and retries are not handled. The returned value is the Promise with answer object.
    ARGUMENTS:
  • url :string - requested URL, for example /assets/product.html

async askForm(url, formData) :Promise<answer>

The askForm method sends a POST request where the body is a new FormData() object. This method is useful for submitting forms and uploading files. It automatically handles multipart/form-data content-type. Note that redirections and retries are not handled by this method. The returned value is a Promise that resolves to an answer object containing details about the request and response.
    ARGUMENTS:
  • url :string - requested URL, for example /assets/product.html
  • formData :FormData - the FormData instance
          // example how to create the form data
          const formData = new FormData();
          formData.append('db_id', db_id);
          formData.append('coll_name', coll_name);
          formData.append('csv_file', csv_file);

object2formdata(formObj) :FormData

Convert JS Object to FormData and use returned value for askForm() parameter.
    ARGUMENTS:
  • formObj :object - object which needs to be converted to FormData

setInterceptor(interceptor) :void

The setInterceptor method sets an interceptor function that will be executed every time before an HTTP request is sent. This can be useful for adding or modifying headers, logging requests, or performing any other actions that need to happen before each request.
    ARGUMENTS:
  • interceptor :Function - A callback function to be executed before each HTTP request is sent. The function receives the HTTPClient instance as its context (this), allowing access to the instance's methods and properties for modification. () => { this.setReqHeader('Authorization', 'JWT some-token); }
// Create an instance of HTTPClient
const httpClient = new HTTPClientFetch({
  timeout: 10000,
  headers: {
    'accept': 'application/json'
  }
});

// Define an interceptor function to set the Authorization header
function authInterceptor() {
  this.setReqHeader('Authorization', 'Bearer your-token');
}

// Set the interceptor
httpClient.setInterceptor(authInterceptor);

// Send a GET request to demonstrate the interceptor in action
httpClient.ask('https://api.example.com/data')
  .then(answer => {
    console.log('Status:', answer.status);
    console.log('Response Content:', answer.res.content);
  })
  .catch(error => {
    console.error('Error:', error);
  });



HTTP Headers

The header name is not case sensitive, so "Authorizaton" or "authorization" can be used.

setReqHeaders(headerObj) :void

Change request header object "this.headers". The headerObj will be appended to previously defined this.headers and headers with the same name will be overwritten.
    ARGUMENTS:
  • headerObj :object - for example: {authorization, 'user-agent', accept, 'cache-control', host, 'accept-encoding', connection}

setReqHeader(headerName, headerValue) :void

Set a request header.
    ARGUMENTS:
  • headerName :string - header name (if headerName already exists in this.headers it will be overwritten)
  • headerValue :string - header value

delReqHeaders(headerNames) :void

Delete multiple request headers.
    ARGUMENTS:
  • headerNames :string[] - array of header names, for example: ['content-type', 'accept']

getReqHeaders() :object

Get request headers as an object.

getResHeaders() :object

Get reponse headers as an object.



Answer Object

The answer object comes as response from request methods like ask(), askOnce(), askJSON, ....
const answer = {
  requestURL:string,
  requestMethod:string,
  status:number,
  statusMessage:string,
  https:boolean,
  req: {
    headers:object,
    payload:any
  },
  res: {
    headers:object,
    content:string|object
  },
  time: {
    req:string,
    res:string,
    duration:number
  }
};


And here is the full object example:
{
        "requestURL": "http://localhost:8001/panel/users/login",
        "requestMethod": "POST",
        "status": 200,
        "statusMessage": "OK",
        "https": false,
        "req": {
            "headers": {
                "authorization": "",
                "accept": "application/json",
                "content-type": "application/json; charset=utf-8"
            },
            "payload": {
                "username": "deva",
                "password": "passMy22gtE$"
            }
        },
        "res": {
            "headers": {
                "content-length": "1025",
                "content-type": "application/json; charset=utf-8"
            },
            "content": {
                "success": true,
                "message": "Login was successful. JWT is generated and you can use it in API request header. Authorization: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwOWY3NGI5Y2Y0NDE5MGEyZDIzN2E2YiIsInVzZXJuYW1lIjoiZGV2YSIsImlhdCI6MTY5MDAyMDE0Mn0.uqGjSwq8Nox-BeNEm-nNi_4Ab03ThOQTlPd3-VBu3QM",
                "jwtToken": "JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkqYVCJ9.eyJpZCI6IjYwOWY3NGI5Y2Y0NDE5MGEyZDIzN2E2YiIsInVHHXJuYW1lIjoiZGV2YSIsImlhdCI6MTY5MDAyMDE0Mn0.uqGjSwq8Nox-BeNEm-nNi_4Ab03ThOQTlPd3-VBu3QM",
                "loggedUser": {
                    "role": "developer",
                    "is_active": true,
                    "login_counter": 52,
                    "connected": false,
                    "_id": "609f74b9cf44190a2d237a6b",
                    "first_name": "Deva",
                    "last_name": "Dev",
                    "address": "roki street 33",
                    "city": "NY",
                    "country": "USA",
                    "email": "deva@test.com",
                    "website": "www.deva.com",
                    "phone": "+1 111222333",
                    "misc": null,
                    "username": "deva",
                    "password": "--removed--",
                    "created_at": "2021-05-15T07:14:01.280Z",
                    "updated_at": "2023-07-20T09:24:24.180Z",
                    "__v": 0,
                    "login_last": "2023-07-20T09:12:53.118Z",
                    "login_last_ip": "93.139.0.224",
                    "ip": "",
                    "port": null,
                    "socketId": ""
                }
            }
        },
        "time": {
            "req": "2023-07-22T10:02:22.600Z",
            "res": "2023-07-22T10:02:22.814Z",
            "duration": 0.214
        }
    }