Base path of the request URL. For example, "/person"
origin?: string
Request URL origin. For example, "https://example.com". Default is the current origin (location.origin).
options?: axios.AxiosRequestConfig
Request Config. See here for more details on options. The options default to the following.
baseURL: string URL with a combination of path and origin parameters.
timeout: number 60000
responseType: string json
withCredentials: boolean true
import {components} from 'metronic-extension';
// If the second parameter origin is omitted, the current origin (location.origin) is used in the request URL.
class PersonApi extends components.Api {
constructor() {
super('/api/persons');
}
}
// The second parameter sets the origin of any request URL.
class CustomerApi extends components.Api {
constructor() {
super('/api/customers', 'https://example.com');
}
}
// The third parameter allows you to set the request configuration.
class OrderApi extends components.Api {
constructor() {
super('/api/orders', 'https://example.com', {
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
});
}
}
protected beforeRequestHook()
Called just before the request. This function receives the request configuration object (axios.AxiosRequestConfig).
Parameters:
config: axios.AxiosRequestConfig
Request Config.
beforeRequestHook(config) {
// Set a token in the request header.
config.headers.Authorization = 'Bearer AbCdEf123456';
}
protected afterResponseHook()
Called immediately after the response. The function receives the response object (axios.AxiosResponse).
Parameters:
res: axios.AxiosResponse
Response object.
afterResponseHook(res) {
if (response.status === 401)
// Alerts when an authentication error occurs.
alert('You are not authorized');
}
protected errorHook()
Called on request errors. This function receives a request error object (axios.AxiosError).
Parameters:
httpStatusCode: number
HTTP status code.
error: axios.AxiosError
Request error object.
errorHook(httpStatusCode, error) {
if (httpStatusCode === 403)
// Redirect in case of authentication error (403).
location.replace('/');
}
public getCancelToken()
Get a token to cancel the request.
Return:
axios.CancelTokenSource A cancellation token.
public isCancel()
Checks the RequestError object to see if the error is due to the request being canceled.
Parameters:
thrown: any
Request Error object.
Return:
boolean True if the error is due to cancellation of the request.
Instance Properties
Name
Description
protected client: axios.AxiosInstance
Axios Instance.
Basic
Create a Person API to retrieve a person with an arbitrary ID.