DevJourney

NodeJS/my-rest-api/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Create User</title>
</head>
<body>
  <h1>Create a New User</h1>
  <form id="createUserForm">
    <label for="userId">ID:</label>
    <input type="number" id="userId" required><br><br>
    
    <label for="userName">Name:</label>
    <input type="text" id="userName" required><br><br>
    
    <button type="submit">Create User</button>
  </form>

  <script>
    document.getElementById('createUserForm').addEventListener('submit', async function (e) {
      e.preventDefault();

      const userId = document.getElementById('userId').value;
      const userName = document.getElementById('userName').value;

      const response = await fetch('http://localhost:3000/users', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ id: userId, name: userName })
      });

      if (response.ok) {
        const data = await response.json();
        alert('User created: ' + JSON.stringify(data));
      } else {
        alert('Error creating user');
      }
    });
  </script>
</body>
</html>
View on GitHub