To establish communication between your client and API, you have the option to utilize AJAX
, using either
the fetch API
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
if (!response.ok) {
// error handling
throw new Error('HTTP error, status = ' + response.status);
}
return response.json();
})
.then(json => console.log(json))
or XMLHttpRequest
let xhttp = new XMLHttpRequest()
xhttp.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', false);
xhttp.onreadystatechange = function(event) {
// XMLHttpRequest.DONE === 4
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
// worked
console.log(this.responseText);
} else {
// error
console.log("Status de la réponse: %d (%s)", this.status, this.statusText);
}
}
};
xhttp.send(null);
Maintaining the connection can be achieved using cookies or session storage
The primary distinction is that cookies are sent as HTTP headers for each request, while localstorage is only accessible within your client's JavaScript
cookie
can be accessed in JavaScript using document.cookie
, which returns a string resembling
name=oeschger; favorite_food=tripe; test1=Hello; test2=World
localStorage
can be accessed with window.localStorage
, providing a Storage
object featuring 5 methods:
Storage.key()
When given a number n, this method will return the name of the nth key in the storage.
Storage.getItem()
When given a key name, it will return that key's value.
Storage.setItem()
When given a key name and value, it will add that key to the storage or update its value if it already exists.
Storage.removeItem()
When given a key name, it will remove that key from the storage.
Storage.clear()
When called, it will clear all keys from the storage.
The method for keeping someone logged in
For auto-login purposes, the process is as follows:
- Check if there is an auth token (random unique string) stored
- If yes, attempt to log in using the token
- If the server accepts, everything is good
- If the server rejects, proceed to the else statement
- Else
- The user logs in normally with their account
- The server responds with an auth token
- Store the token as needed
Auth tokens should have a limited lifespan (it's illegal for cookies to last longer than a year in Europe)
One token per account at most; a new token invalidates the previous one
For more information on the process, visit