【发布时间】: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