v0.8
HTTPClient
class HTTPClient → file: core/lib/HTTPClient.jsHTTPClient can be used in the controller to send HTTP request to HTTP/S servers. In most cases it will be used to fetch the JSON data from API.
Instance
Instance created withnew HTTPClient(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 | |
req_headers | default request headers | object | |
xhr | instance of the XMLHttpRequest | XMLHttpRequest | |
interceptor | A function which will be executed before the HTTP request is sent. It's defined by the setInterceptor(). | Function |
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 |
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: '*/*'} |
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<answer>
Sending one HTTP request to HTTP server. The returned value is the Promise with answer object.- 301 redirections are handled.
- retries are handled
-
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 sendFormData(url, formData) :Promise<answer>
Send POST request where body is new FormData() object. 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
-
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 sendFormData() parameter.-
ARGUMENTS:
- formObj :object - object which needs to be converted to FormData
kill() :void
Stop the sent request immediatelly.setInterceptor(interceptor) :void
Set the interceptor function which will be executed every time before the HTTP request is sent.-
ARGUMENTS:
- interceptor :Function - callback function, for example
(httpClient) => { httpClient.setReqHeader('Authorization', 'JWT aswas); }
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 } }