Preview:
//index.html
<!DOCTYPE html>
<html>
<head>
  <title>Login</title>
</head>
<body>
  <h2>Login</h2>
  <input id="email" placeholder="Email" required><br>
  <input id="password" type="password" placeholder="Password" required><br>
  <button onclick="login()">Login</button>
  <p>No account? <a href="register.html">Register here</a></p>

  <script>
    const API = 'http://localhost:5000/api/auth';

    async function login() {
      const email = document.getElementById('email').value;
      const password = document.getElementById('password').value;

      if (!email || !password) {
        alert("Please fill in all fields");
        return;
      }

      try {
        const res = await fetch(`${API}/login`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email, password })
        });

        const data = await res.json();

        if (res.ok) {
          localStorage.setItem('token', data.token);
          alert('Login successful!');
          window.location.href = 'tasks.html';
        } else {
          alert(data.message || 'Login failed');
        }
      } catch (err) {
        console.error('Login error:', err);
        alert('Something went wrong. Please try again.');
      }
    }
  </script>
</body>
</html>


//register.html
<!DOCTYPE html>
<html>
<head>
  <title>Register</title>
</head>
<body>
  <h2>Register</h2>
  <input id="name" placeholder="Full Name" required><br>
  <input id="email" placeholder="Email" required><br>
  <input id="password" type="password" placeholder="Password" required><br>
  <button id="registerBtn">Register</button>
  <p>Already have an account? <a href="index.html">Login here</a></p>

  <script>
    const API = 'http://localhost:5000/api/auth';

    document.getElementById('registerBtn').addEventListener('click', async () => {
      const name = document.getElementById('name').value;
      const email = document.getElementById('email').value;
      const password = document.getElementById('password').value;

      if (!name || !email || !password) {
        return alert('All fields are required.');
      }

      try {
        const res = await fetch(`${API}/register`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ name, email, password })
        });

        const data = await res.json();

        if (res.ok) {
          alert(data.message);
          window.location.href = 'index.html';
        } else {
          alert(data.message || 'Registration failed');
        }
      } catch (err) {
        console.error('Register error:', err);
        alert('Something went wrong. Try again.');
      }
    });
  </script>
</body>
</html>


//tasks.html

<!DOCTYPE html>
<html>
<head>
  <title>Task Management</title>
</head>
<body>
  <h2>Manage Your Tasks</h2>

  <div>
    <input id="taskTitle" placeholder="Enter Task Title"><br>
    <input id="taskDescription" placeholder="Enter Description"><br>
    <input id="taskDueDate" type="date"><br>
    <select id="taskStatus">
      <option value="pending">Pending</option>
      <option value="in-progress">In Progress</option>
      <option value="completed">Completed</option>
    </select><br><br>
    <button onclick="addNewTask()">Add New Task</button>
  </div>

  <h3>Task List</h3>
  <ul id="taskList"></ul>

  <script>
    const API_URL = 'http://localhost:5000/api/tasks';
    const userToken = localStorage.getItem('token');

    if (!userToken) {
      alert("You need to log in first.");
      window.location.href = "login.html"; // Redirect to login page if no token found
    }

    // Fetch and display all tasks
    async function getAllTasks() {
      try {
        const response = await fetch(API_URL + '/all', {
          headers: { Authorization: 'Bearer ' + userToken }
        });
        const tasks = await response.json();

        const taskListElement = document.getElementById('taskList');
        taskListElement.innerHTML = '';

        if (tasks.length === 0) {
          taskListElement.innerHTML = '<li>No tasks found.</li>';
        } else {
          tasks.forEach(task => {
            const taskItem = document.createElement('li');
            taskItem.innerHTML = `
              <b>${task.title}</b> - ${task.status}
              <button onclick="deleteTask('${task._id}')">Delete</button>
            `;
            taskListElement.appendChild(taskItem);
          });
        }
      } catch (err) {
        console.error("Fetching tasks failed:", err);
        alert("Error fetching tasks. Please try again.");
      }
    }

    // Add a new task
    async function addNewTask() {
      const title = document.getElementById('taskTitle').value.trim();
      const description = document.getElementById('taskDescription').value.trim();
      const dueDate = document.getElementById('taskDueDate').value;
      const status = document.getElementById('taskStatus').value;

      if (!title) {
        return alert("Title is required.");
      }

      try {
        const response = await fetch(API_URL + '/create', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: 'Bearer ' + userToken
          },
          body: JSON.stringify({ title, description, dueDate, status })
        });

        const responseData = await response.json();
        alert('Task added successfully!');
        getAllTasks();
      } catch (err) {
        console.error("Adding task failed:", err);
        alert("Could not add task.");
      }
    }

    // Delete a task by ID
    async function deleteTask(taskId) {
      if (!confirm("Are you sure you want to delete this task?")) return;

      try {
        const response = await fetch(`${API_URL}/delete/${taskId}`, {
          method: 'DELETE',
          headers: { Authorization: 'Bearer ' + userToken }
        });

        const responseData = await response.json();
        alert(responseData.message);
        getAllTasks();
      } catch (err) {
        console.error("Deleting task failed:", err);
        alert("Could not delete task.");
      }
    }

    // Load tasks when the page loads
    getAllTasks();
  </script>
</body>
</html>
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter