mysql 为什么DELETE和PUT方法在我的网站上不起作用?

tnkciper  于 2023-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(137)

即时通讯建设一个基本的网站,作为任务管理应用程序。每个HTTP方法都有一个端点。正在使用的方法是:GET、POST、PUT和DELETE。它们必须被链接以添加、编辑和删除任务,设置到期日和提醒,并将任务组织到类别或项目中。但问题是我的删除和编辑按钮不起作用。我要提供的HTML,和,客户端和服务器端JS。

<!DOCTYPE html>
<html>
  <head>
    <title>Task.me</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <header>
      <img src="logo.png" alt="Task.me Logo" id="logo">
      <h1>Task.me</h1>
    </header>
    <main>
      <form id="add-task-form">
        <h2>Add Task</h2>
        <div class="form-group">
          <label for="new-task">Task:</label>
          <input type="text" id="new-task">
        </div>
        <div class="form-group">
          <label for="due-date">Due Date:</label>
          <input type="date" id="due-date">
        </div>
        <div class="form-group">
          <label for="category">Category:</label>
          <select id="category">
            <option value="">--Select a category--</option>
            <option value="Personal">Personal</option>
            <option value="Work">Work</option>
            <option value="School">School</option>
          </select>
        </div>
        <button>Add</button>
      </form>
      <section id="tasks-section">
        <h2>Tasks</h2>
        <ul id="task-list">
          <!-- List of tasks will go here -->
        </ul>
      </section>
    </main>

    <!-- Template for displaying tasks -->
    <template id="task-template">
      <li class="task-item">
        <form class="edit-task-form" hidden>
          <div class="form-group">
            <label>Task:</label>
            <input type="text" class="edit-task-name">
          </div>
          <div class="form-group">
            <label>Due Date:</label>
            <input type="date" class="edit-due-date">
          </div>
          <div class="form-group">
            <label>Category:</label>
            <select class="edit-category">
              <option value="">--Select a category--</option>
              <option value="Personal">Personal</option>
              <option value="Work">Work</option>
              <option value="School">School</option>
            </select>
          </div>
          <button>Save</button>
          <button type="button" class="cancel-button">Cancel</button>
        </form>
        <div class="view-task">
          <span class="task-name"></span>
          <span class="due-date"></span>
          <span class="category"></span>
          <button class="edit-button">Edit</button>
          <button class="delete-button">Delete</button>
        </div>
      </li>
    </template>

    <!-- Your HTML code goes here -->
    <script src="script.js"></script>

  </body>

</html>

JS客户端

// CLIENT SIDE

// Function for retrieving tasks from the web service
async function getTasks() {
    const response = await fetch("/tasks");
    const tasks = await response.json();
    return tasks;
}

// Function for adding a new task using the web service
async function addTask(name, dueDate, category) {
    const response = await fetch("/tasks", {
        method:"POST",
        headers:{
            "Content-Type":"application/json"
        },
        body:JSON.stringify({name,dueDate,category})
    });
    const newTask = await response.json();
    return newTask
}

// Function for updating an existing task using the web service
async function updateTask(id, name, dueDate, category) {
    const response = await fetch(`/tasks/${id}`,{
        method:"PUT",
        headers:{
            "Content-Type":"application/json"
        },
        body:JSON.stringify({name,dueDate,category})
    });
    const updatedTask = await response.json();
    return updatedTask
}

// Function for deleting an existing task using the web service
async function deleteTask(id) {
    const response = await fetch(`/tasks/${id}`,{
        method:"DELETE"
    });
    return response.ok
}

// Function for displaying tasks on the HTML page
async function displayTasks() {
    const tasks = await getTasks();
    console.log("Tasks:", tasks); // added console.log statement
    const taskListElement = document.querySelector("#task-list");
    const taskTemplate = document.querySelector("#task-template");
    taskListElement.innerHTML = "";
    for (const task of tasks) {
        const taskElement = taskTemplate.content.cloneNode(true);
        taskElement.querySelector(".task-name").textContent = task.name;
        taskElement.querySelector(".due-date").textContent = task.dueDate;
        taskElement.querySelector(".category").textContent = task.category;
        taskElement.querySelector(".edit-button").dataset.taskId = task.id;
        taskElement.querySelector(".delete-button").dataset.taskId = task.id;
        taskListElement.appendChild(taskElement);
    }
}

// Function for handling the submit event of the add-task form
function handleAddTaskFormSubmit(event) {
    event.preventDefault();
    const form = event.currentTarget;
    const name = form.elements["new-task"].value;
    const dueDate = form.elements["due-date"].value;
    const category = form.elements["category"].value;
    addTask(name, dueDate, category)
        .then(() => displayTasks())
        .catch(error => console.error(error));
}

// Function for handling the click event of the edit buttons
function handleEditButtonClick(event) {
    console.log("Edit button clicked"); // added console.log statement
    const taskId = parseInt(event.currentTarget.dataset.taskId);
    console.log("Task ID:", taskId); // added console.log statement
    const taskElement = event.currentTarget.closest(".task-item");
    console.log("Task element:", taskElement); // added console.log statement
    if (taskElement) {
        const viewTaskElement = taskElement.querySelector(".view-task");
        const editTaskForm = taskElement.querySelector(".edit-task-form");
        viewTaskElement.hidden = true;
        editTaskForm.hidden = false;
        
        // added code to populate edit-task form with current values
        editTaskForm.elements["edit-task-name"].value = viewTaskElement.querySelector(".task-name").textContent;
        editTaskForm.elements["edit-due-date"].value = viewTaskElement.querySelector(".due-date").textContent;
        editTaskForm.elements["edit-category"].value = viewTaskElement.querySelector(".category").textContent;
    }
}


// Function for handling the submit event of the edit-task forms
function handleEditTaskFormSubmit(event) {
    event.preventDefault();
    const form = event.currentTarget;
    const taskId = parseInt(form.closest(".task-item").querySelector(".edit-button").dataset.taskId);
    const name = form.elements["edit-task-name"].value;
    const dueDate = form.elements["edit-due-date"].value;
    const category = form.elements["edit-category"].value;
    updateTask(taskId, name, dueDate, category)
        .then(() => displayTasks())
        .catch(error => console.error(error));
}

// Function for handling the click event of the cancel buttons
function handleCancelButtonClick(event) {
    const taskId = parseInt(event.currentTarget.closest(".task-item").querySelector(".edit-button").dataset.taskId);
    const taskElement = event.currentTarget.closest(".task-item");
    const viewTaskElement = taskElement.querySelector(".view-task");
    const editTaskForm = taskElement.querySelector(".edit-task-form");
    viewTaskElement.hidden = false;
    editTaskForm.hidden = true;
}

// Function for handling the click event of the delete buttons
function handleDeleteButtonClick(event) {
    const taskId = parseInt(event.currentTarget.dataset.taskId);
    deleteTask(taskId)
        .then(() => displayTasks())
        .catch(error => console.error(error));
}

// Add event listeners when the page loads
window.addEventListener("load", () => {
    // Display tasks when the page loads
    displayTasks();

    // Add event listener for the submit event of the add-task form
    const addTaskForm = document.querySelector("#add-task-form");
    addTaskForm.addEventListener("submit", handleAddTaskFormSubmit);

    // Add event listeners for the click event of the edit, delete, and cancel buttons
    // and the submit event of the edit-task forms
    // using event delegation
    const taskListElement = document.querySelector("#task-list");
    taskListElement.addEventListener("click", event => {
        if (event.target.matches(".edit-button")) {
            handleEditButtonClick(event);
        } else if (event.target.matches(".delete-button")) {
            handleDeleteButtonClick(event);
        } else if (event.target.matches(".cancel-button")) {
            handleCancelButtonClick(event);
        }
    });
    taskListElement.addEventListener("submit", event => {
        if (event.target.matches(".edit-task-form")) {
            handleEditTaskFormSubmit(event);
        }
    });
});

服务器端

// server/index.js
const bodyParser = require("body-parser");
const path = require('path');
const express = require("express");
const mysql = require("mysql"); // added require statement for mysql module

const PORT = process.env.PORT || 3001;
const app = express();

app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));

app.get("/api", (req, res) => {
    res.sendFile(__dirname + "/public/home.html");
});

// Create a connection to the MySQL database
const connection = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "tasks_db"
});

// Connect to the MySQL database
connection.connect();

// GET endpoint for retrieving all tasks
app.get("/tasks", (req, res) => {
  connection.query("SELECT * FROM tasks", (error, results) => {
    if (error) {
      res.status(500).send(error);
    } else {
      res.json(results);
    }
  });
});

// POST endpoint for adding a new task
app.post("/tasks", (req, res) => {
  const newTask = {
    name: req.body.name,
    dueDate: req.body.dueDate,
    category: req.body.category
  };
  connection.query("INSERT INTO tasks SET ?", newTask, (error, results) => {
    if (error) {
      res.status(500).send(error);
    } else {
      newTask.id = results.insertId;
      res.json(newTask);
    }
  });
});

// PUT endpoint for updating an existing task
app.put("/tasks/:id", (req, res) => {
  const taskId = parseInt(req.params.id);
  const updatedTask = {
    name: req.body.name,
    dueDate: req.body.dueDate,
    category: req.body.category
  };
  connection.query("UPDATE tasks SET ? WHERE id = ?", [updatedTask, taskId], (error, results) => {
    if (error) {
      res.status(500).send(error);
    } else if (results.affectedRows === 0) {
      res.status(404).send("Task not found");
    } else {
      updatedTask.id = taskId;
      res.json(updatedTask);
    }
  });
});

// DELETE endpoint for deleting an existing task
app.delete("/tasks/:id", (req, res) => {
  const taskId = parseInt(req.params.id);
  connection.query("DELETE FROM tasks WHERE id = ?", taskId, (error, results) => {
    if (error) {
      res.status(500).send(error);
    } else if (results.affectedRows === 0) {
      res.status(404).send("Task not found");
    } else {
      res.sendStatus(204);
    }
  });
});

app.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
});

单击DELETE AND EDIT TASK按钮时遇到的错误是(以下错误来自浏览器的开发人员工具):

EDIT BUTTON CLICKED: 
Task ID:NaN
Task element: -null

DELETE BUTTON CLICKED:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
RESPONSE: 
{
    "code": "ER_BAD_FIELD_ERROR",
    "errno": 1054,
    "sqlMessage": "Unknown column 'NaN' in 'where clause'",
    "sqlState": "42S22",
    "index": 0,
    "sql": "DELETE FROM tasks WHERE id = NaN"
}

此外,我使用连接到MYSQL的数据库。DATABASE SETUP
似乎不明白问题出在哪里。我真的很感激你的帮助。拜托

wljmcqd8

wljmcqd81#

更新js文件中handleEditButtonClick函数的任务。

const taskId = parseInt(event.currentTarget.dataset.taskId);

更新js文件中handleDeleteButtonClick函数的任务。

const taskId = parseInt(event.currentTarget.dataset.taskId);

确保你有一个主键。

相关问题