【发布时间】:2021-10-20 17:41:42
【问题描述】:
所以我是 JS 新手,我在网上找到的解决方案都没有对我有用。我正在为 todolist 创建一个后端,并且我想添加 app.delete 功能,以便我可以从列表中删除项目。
这是我单独的 json 文件中的代码:
[{"id":1,"name":"item 1","complete":true},{"id":2,"name":"Walk the dog","complete":false},{"id":3,"name":"Go shopping","complete":false}]
这是我尝试过的,但老实说,我只是写了我想到的任何东西:
app.delete('/todo/:id/delete', (request, response) => {
const id = request.params.id
const findTodobyID = (todos, id) => {
for(let i = 0; i < todos.length; i++){
if(todos[i].id === parseInt(id)){
return i
}
}
return -1
}
fs.readFile('./store/todos.json', 'utf-8', (err, data) => {
if(err) {
return response.status(500).send('Sorry, something went wrong.')
}
let todos = JSON.parse(data)
const todoIndex = findTodobyID(todos, id)
if (todoIndex === -1) {
return response.status(404).send('Sorry, ID not found')
}
todos[todoIndex].complete = true
fs.writeFile('./store/todos.json', JSON.delete(todos), () => {
return response.json({'status': 'Deleted ID' + id})
})
})
})
这是我在 Postman 中运行时遇到的错误:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot DELETE /todos/3/delete</pre>
</body>
</html>
【问题讨论】:
-
仅供参考,有一个内置方法
Array.prototype.findIndex可以完成您的findTodobyID函数的工作。 -
如果您要删除它,那么设置
complete属性是没有意义的。
标签: javascript node.js json express postman