Ajax operations
Just syntax sugar over the standard fetch API.
Methods
# async static request(params)
Encapsulate the Fetch API to automate:
- Content-Type header
- Authorization header (Bearer) using the Json Web Token provided by kiss.session
- Body parsing
- Timeout management (default to 60000 ms)
- Automatically sets the "boundary" parameter for multipart/form-data content
- Process HTTP error codes: . 401 redirects to login page . 403 (forbidden) sends a notification . 498 (token expired) tries to get a new token using the refresh token, and redirects to login if failed
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
params |
object
|
A single object containing the following: |
|
host |
string
|
<optional> |
Optional host to prepend to the URL in replacement of the default host |
url |
string
|
Url to request |
|
method |
string
|
get, post, put, patch, delete, options - Default to get |
|
accept |
object
|
Accept header |
|
contentType |
object
|
Content Type header - Default to application/json; charset=UTF-8 |
|
authorization |
object
|
Authorization header |
|
accessControlAllowOrigin |
object
|
Access Control Allow Origin |
|
accessControlAllowHeaders |
object
|
Access Control Allow Headers |
|
body |
object
|
string
|
body for post, put and patch requests |
|
timeout |
number
|
in milliseconds. Throw an error in timeout exceeded. |
|
showLoading |
boolean
|
If true, show the loading spinner while loading - Default to false |
Request's result, or false if it failed
Example
// Posting with simple JSON:
kiss.ajax.request({
url: YOUR_URL,
method: "post",
accept: "application/json",
contentType: "application/json; charset=UTF-8",
body: JSON.stringify({
foo: "bar",
hello: "world"
}),
timeout: 500
})
.then(data => {
console.log(data)
})
.catch(err => {
console.log(err)
})
// Posting with basic authentication and application/x-www-form-urlencoded:
kiss.ajax.request({
url: YOUR_URL,
method: "post",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
authorization: "Basic " + btoa(YOUR_LOGIN + ":" + YOUR_PASSWORD),
body: "foo=bar&hello=world"
})
# static setHeaders(headers)
Set the request headers
Parameters:
Name | Type | Description |
---|---|---|
headers |
object
|
Example
kiss.ajax.setHeaders({
"Accept": "application/json",
"Content-Type": "application/json; charset=UTF-8"
})
# static setHost(host)
Set the host for the requests. You can use this method to set the base URL for the requests.
Parameters:
Name | Type | Description |
---|---|---|
host |
string
|
Example
kiss.ajax.setHost("https://api.example.com:3000")
# static setTimeout(timeout)
Adjust the request timeout
Parameters:
Name | Type | Description |
---|---|---|
timeout |
number
|
in milliseconds |