首页 > 解决方案 > PRN 项目修改数据库中的所有条目而不是指定的条目

问题描述

我在空闲时间一直在研究图书馆应用程序,但遇到了一个我无法弄清楚的问题。我正在尝试更新特定书籍的信息,但是,每次我更新这本书时,它都会应用于数据库中的所有条目,而不是预期的条目,显然这是个问题。我已经尝试了所有我能想到的让程序仅将更改应用于相关项目的方法。它是一个 PRN 堆栈应用程序。任何想法将不胜感激!

Express 端(在 PostgreSQL 中自动生成 library_id

//update book

app.put("/update/:library_id", async (req, res) => {
  try {
    const { title } = req.body;
    const { author } = req.body;
    const { genre } = req.body;
    const { published } = req.body;
    const { description } = req.body;
    const updateBook = await pool.query(
      "UPDATE library SET title = $1, author = $2, genre = $3, published = $4, description = $5 WHERE library_id = library_id",
      [title, author, genre, published, description]
    );

    res.json("book was updated");
  } catch (err) {
    console.error(err.message);
  }
});

React.js 端

function EditBook({ book }) {
  console.log(book);
  const [title, setTitle] = useState(book.title);
  const [author, setAuthor] = useState(book.author);
  const [genre, setGenre] = useState(book.genre);
  const [published, setPublished] = useState(book.published);
  const [description, setDescription] = useState(book.description);

  //update method
  const updateBook = async (e) => {
    e.preventDefault();
    try {
      const body = { title, author, genre, published, description };
      const response = await fetch(
        `http://localhost:5000/update/${book.library_id}`,
        {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(body),
        }
      );

      window.location = "/";
      console.log(response);
    } catch (err) {
      console.error(err.message);
    }
  };

提前致谢!

标签: node.jsreactjsdatabasepostgresqlexpress

解决方案


推荐阅读