无法获取表单数据到节点服务器

问题描述 投票:0回答:1

我正在尝试从表单获取数据以转到我的本地节点服务器,但它没有显示在终端中。 我对这一切都很陌生,所以请原谅任何菜鸟错误。

这就是我打算如何进行的:

当您填写 HTML 表单并提交时,表单的详细信息应显示在服务器终端中。 我稍后打算使用这些数据来填充另一个 html 页面,这就是为什么我想在终端中看到它以了解数据是否被正确接收和处理。 我希望这是有道理的。

我的html代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- Compiled and minified CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <title>Task Managing App</title>
  <style>
    /* Custom CSS */
    .input-field label {
      color: #9e9e9e !important;
    }
  </style>
</head>
<body style="background-color: #1f2631;">
  <div class="container">
    <div class="row">
      <div style="margin-top: 2rem;" class="col s12 m10 offset-m1 l8 offset-l2 xl6 offset-xl3 section">
        <div class="card" style="border-radius: 12px;">
          <div class="card-content" >
            <span class="card-title">Task Managing App</span>
            <form id="task-form" action="http://localhost:3000/store-task" method="POST">
              <div class="input-field">
                <input type="text" name="task" id="task" required>
                <label for="task">Task Name <span style="color: red;">*</span></label>
              </div>
              <div class="input-field">
                <input type="text" name="category" id="category" required>
                <label for="category">Task Category <span style="color: red;">*</span></label>
              </div>
              <div class="input-field">
                <textarea name="description" id="description" class="materialize-textarea"></textarea>
                <label for="description">Task Description</label>
              </div>
              <div class="input-field">
                <input type="text" name="deadline" id="deadline" required>
                <label for="deadline">Deadline (DD/MM/YYYY) <span style="color: red;">*</span></label>
              </div>
              <div class="input-field">
                <p>
                  <label>
                    <input type="checkbox" name="reminder" id="reminder" />
                    <span style="color: #9e9e9e;">Reminder</span>
                  </label>
                </p>
              </div>
              <div id="reminder-options" style="display: none;">
                <div class="row">
                  <div class="input-field col s6">
                    <select name="frequency" id="frequency">
                      <option value="" disabled selected>Choose frequency</option>
                      <option value="30mins">30 mins before</option>
                      <option value="1hour">1 hour before</option>
                      <option value="1day">1 day before</option>
                      <option value="3days">3 days before</option>
                      <option value="1week">1 week before</option>
                    </select>
                    <label for="frequency">Reminder Frequency</label>
                  </div>
                  <div class="input-field col s6">
                    <select name="notification" id="notification">
                      <option value="" disabled selected>Choose notification type</option>
                      <option value="email">Email</option>
                      <option value="notifications">Notifications</option>
                    </select>
                    <label for="notification">Notification Type</label>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="col s6 left-align">
                  <button class="btn waves-effect waves-light red" type="button" onclick="window.location.href='homepage.html'">
                    Cancel
                  </button>
                </div>
                <div class="col s6 right-align">
                  <button class="btn waves-effect waves-light" type="submit" name="action">
                    Create Task
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- jQuery 3.5.1 uncompressed -->
  <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
  <!-- Compiled and minified JavaScript -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>
</html>

我的app.js代码:

/** @format */
////////////////////////////////////////////////////////////////////////////////
// Declaring, identifying and initializing UI Variables
////////////////////////////////////////////////////////////////////////////////
const form = document.querySelector('#task-form');
const inputTask = document.querySelector('#task');
const inputCategory = document.querySelector('#category');
const inputDescription = document.querySelector('#description');
const inputDeadline = document.querySelector('#deadline');
const reminderCheckbox = document.querySelector('#reminder');
const frequencySelect = document.querySelector('#frequency');
const notificationSelect = document.querySelector('#notification');
const taskList = document.querySelector('.collection');
const clearTasks = document.querySelector('.clear-btn');

////////////////////////////////////////////////////////////////////////////////
// Load all event listeners
////////////////////////////////////////////////////////////////////////////////
loadEventListener();

function loadEventListener() {
  // Loads stored tasks
  document.addEventListener('DOMContentLoaded', loadTasks);
  //Add task event
  form.addEventListener('submit', addTask);
  //Remove task
  taskList.addEventListener('click', deleteTask);
  // Clear Task List
  clearTasks.addEventListener('click', clearTaskList);
  // Show/hide reminder options
  reminderCheckbox.addEventListener('change', toggleReminderOptions);
}

////////////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////////////

// Load tasks from local storage on page start
function loadTasks() {
  let tasks;
  if (localStorage.getItem('tasks') === null) {
    tasks = [];
  } else {
    tasks = JSON.parse(localStorage.getItem('tasks'));
  }
  tasks.forEach(function (task) {
    createNewTaskElement(task);
  });
}

//Creates li & a-Tag element and adds it to the ul
function createNewTaskElement(task) {
  const newTask = document.createElement('li');
  newTask.className = 'collection-item';
  newTask.innerHTML = `
    <div>${task.task}</div>
    <div>${task.category}</div>
    <div>${task.description}</div>
    <div>${task.deadline}</div>
  `;
  const newTaskATag = document.createElement('a');
  newTaskATag.style.cursor = 'pointer';
  newTaskATag.style.color = '#e01a4f';
  newTaskATag.className = 'delete-item secondary-content';
  newTaskATag.innerHTML = '<i class="material-icons">delete</i>';

  newTask.appendChild(newTaskATag);

  taskList.appendChild(newTask);
}

// Adds a new task to the Task List
function addTask(e) {
  e.preventDefault(); // Prevent the default form submission

  // Retrieve form data from input fields
  const taskData = {
    task: inputTask.value,
    category: inputCategory.value,
    description: inputDescription.value,
    deadline: inputDeadline.value,
    reminder: reminderCheckbox.checked,
    frequency: frequencySelect.value,
    notification: notificationSelect.value
  };

  // Log the form data for debugging
  console.log(taskData);

  // Send the form data to the server
  fetch('/store-task', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(taskData)
  })
  .then(response => {
    if (response.ok) {
      console.log('Task added successfully');
      // Redirect to homepage or perform other actions as needed
    } else {
      throw new Error('Failed to add task'); // Throw an error if response is not ok
    }
  })
  .catch(error => {
    console.error('Error adding task:', error);
    // Handle the error here (e.g., display an error message to the user)
  });
}



// Saves task to local storage
function storeTaskInLocalStorage(task) {
  let tasks;
  if (localStorage.getItem('tasks') === null) {
    tasks = [];
  } else {
    tasks = JSON.parse(localStorage.getItem('tasks'));
  }

  tasks.push(task);

  localStorage.setItem('tasks', JSON.stringify(tasks));
}

// Deletes a single task from the task list
function deleteTask(e) {
  if (e.target.parentElement.classList.contains('delete-item')) {
    if (confirm('Are you sure?')) {
      e.target.parentElement.parentElement.remove();

      removeTaskFromLocalStorage(
        e.target.parentElement.parentElement.firstChild.textContent
      );
    }
  }
}

// Delete task from local storage
function removeTaskFromLocalStorage(taskToDelete) {
  let tasks;
  tasks = JSON.parse(localStorage.getItem('tasks'));
  tasks.forEach(function (task, index) {
    if (task.task === taskToDelete) {
      tasks.splice(index, 1);
    }
  });
  localStorage.setItem('tasks', JSON.stringify(tasks));
}

// Show/hide reminder options
function toggleReminderOptions() {
  const reminderOptions = document.getElementById('reminder-options');
  if (this.checked) {
    reminderOptions.style.display = 'block';
  } else {
    reminderOptions.style.display = 'none';
  }
}

// Deletes all tasks from taskList
function clearTaskList() {
  while (taskList.firstChild) {
    taskList.removeChild(taskList.firstChild);
  }
  localStorage.clear();
}

我的server.js代码:

const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
const path = require('path'); // Import the path module

// Middleware to parse JSON bodies
app.use(express.json());

// Serve the homepage.html file
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'homepage.html'));
});

// POST endpoint to store task data
app.post('/store-task', (req, res) => {
    try {
        const taskData = req.body;
        console.log('Received task data:', taskData);
  
        // Check if taskData is empty or null
        if (!taskData) {
          throw new Error('Invalid task data');
        }
  
        // Here, you can store the task data in a database or perform other actions
  
        // Send a success response
        res.sendStatus(200);
    } catch (error) {
        console.error('Error processing task data:', error);
        // Send an error response
        res.status(500).send('Internal server error');
    }
});


// Start the server
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

这是我在终端中收到的响应:

Server is running on port 3000
Received task data: {}

我什至将以下内容添加到 server.js 文件中的 app.post

    const taskData = req.body;
    console.log('Received task data:', taskData);
    console.log('Received task data:');
    console.log('Task:', taskData.task);
    console.log('Category:', taskData.category);
    console.log('Description:', taskData.description);
    console.log('Deadline:', taskData.deadline);
    console.log('Reminder:', taskData.reminder);
    console.log('Frequency:', taskData.frequency);
    console.log('Notification:', taskData.notification);

但得到的回应是:

Received task data: {}
Received task data:
Task: undefined
Category: undefined
Description: undefined
Deadline: undefined
Reminder: undefined
Frequency: undefined
Notification: undefined
javascript html node.js json post
1个回答
0
投票

您可以尝试以下方法,

替换以下内容:

    ////////////////////////////////////////////////////////////////////////////////
// Declaring, identifying and initializing UI Variables
////////////////////////////////////////////////////////////////////////////////
const form = document.querySelector('#task-form');
const inputTask = document.querySelector('#task');
const inputCategory = document.querySelector('#category');
const inputDescription = document.querySelector('#description');
const inputDeadline = document.querySelector('#deadline');
const reminderCheckbox = document.querySelector('#reminder');
const frequencySelect = document.querySelector('#frequency');
const notificationSelect = document.querySelector('#notification');
const taskList = document.querySelector('.collection');
const clearTasks = document.querySelector('.clear-btn');

 ////////////////////////////////////////////////////////////////////////////////
// Load all event listeners
////////////////////////////////////////////////////////////////////////////////
loadEventListener();

let clearTasks,form,frequencySelect;
let inputCategory,inputDescription,inputDeadline,inputTask;
let notificationSelect,reminderCheckbox,taskList;

window.addEventListener('load', ()=>{
    form = document.querySelector('#task-form');
    inputTask = document.querySelector('#task');
    inputCategory = document.querySelector('#category');
    inputDescription = document.querySelector('#description');
    inputDeadline = document.querySelector('#deadline');
    reminderCheckbox = document.querySelector('#reminder');
    frequencySelect = document.querySelector('#frequency');
    notificationSelect = document.querySelector('#notification');
    taskList = document.querySelector('.collection');
    clearTasks = document.querySelector('.clear-btn');
    loadEventListener();
}); 
© www.soinside.com 2019 - 2024. All rights reserved.