Browser and Web APIs

Exercise: AJAX Requests

  1. Implement the request functions of the JavaScript login:
    • loginUser sends a POST request to the authentication endpoint and navigates to the chat page, passing the received token as a query parameter:
      location.href = 'chat.html?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
    • registerUser sends a POST request to the users endpoint and calls the loginUser function
    If an error occurs, an appropriate error message is displayed.
  2. In the JavaScript chat retrieve the authentication token from the query parameters:
    const token = new URLSearchParams(location.search).get('token');
    Use the token to implement the request functions:
    • fetchMessages sends a GET request to the messages endpoint and renders the recevied messages
    • postMessage sends a POST request to the messages endpoint
    If an authentication error occurs, the user is redirected to the login page.
  3. Invoke the fetchMessages repeatedly (e.g. every 10 seconds) so that the chat messages are automatically refreshed.