【问题标题】:Using React, NodeJS, and Postgres: Having trouble being able to delete and updating todos使用 React、NodeJS 和 Postgres:无法删除和更新 todos
【发布时间】:2021-06-08 10:44:30
【问题描述】:

我正在使用 postgre 和 react 创建简单的待办事项应用程序。

服务器端的删除和更新定义如下。

app.put("/todos/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const { description } = req.body;
    const updateTodo = await pool.query(
      "update todo set description = $1 where todo_id = $2",
      [description, id]
    );
    res.json("todo updated !!");
  } catch (error) {
    console.error(error.message);
  }
});

// delete todo
app.delete("/todos/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const deleteTodo = await pool.query("delete from todo where todo_id = $1", [
      id,
    ]);
    res.json("todo deleted !!");
  } catch (error) {
    console.error(error.message);
  }
});

在前端(React)这就是我调用更新和删除的方式

  const updateDescription = async () => {
    try {
      handleClose();
      const body = { description };
      const response = fetch(`http://localhost:3000/${todo.todo_id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      console.log(response);
    } catch (error) {
      console.log(error.message);
    }
  };



删除待办事项在其他组件中。

  const deleteTodo = async (id) => {
    try {
      const deleteTodo = await fetch(`http://localhost:3000/${id}`, {
        method: "DELETE ",
      });
      console.log(deleteTodo);
      setTodods(todos.filter((todo) => todo.todo_id !== id));
    } catch (error) {
      console.log(error.message);
    }
  };

所以当我执行删除或提出请求时,它不会在数据库中更新它。

在浏览器控制台上我收到此错误。

Failed to execute 'fetch' on 'Window': 'DELETE ' is not a valid HTTP method.

已编辑

Response {type: "cors", url: "http://localhost:3000/3", redirected: false, status: 404, ok: false, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 404
statusText: "Not Found"
type: "cors"
url: "http://localhost:3000/3"
__proto__: Response

对于插入待办事项它的工作,但对于删除和放置请求,它不会在数据库中更新。

那么有人可以告诉我这里出了什么问题吗?

【问题讨论】:

    标签: node.js reactjs postgresql express


    【解决方案1】:

    DELETE 后面有一个空格,更正它应该可以正常工作。即使它是一个简单的待办事项应用程序,当我们处理固定字符串时,创建enumconst 总是很好的做法,即我们知道字符串不会改变,以便我们可以保持一致性并跳过这些类型的问题。

    const METHOD = {
     GET: "GET",
     PUT: "PUT",
     POST: "POST",
     DELETE: "DELETE" 
    };
    

    【讨论】:

    • 这有帮助。但是 ts 只在前端更新。但是数据库没有更新。我在浏览器控制台上收到其他错误。你可以在编辑部分看到。
    • 我认为您正在尝试对不存在的资源执行一些操作。您什么时候看到新错误,是 PUT 还是 DELETE ?
    • 删除时。如果我在邮递员上执行它在数据库中删除它,则该资源是存在的。
    • 酷。我知道了。它的删除网址错误。应该是 ` const deleteTodo = await fetch(http://localhost:3000/todos/${id}, { method: "DELETE", });`
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 2022-11-28
    • 1970-01-01
    • 2022-07-13
    • 1970-01-01
    • 1970-01-01
    • 2014-08-11
    相关资源
    最近更新 更多