javascript - 删除 http://localhost:3000/people/[object%20Object] 404(未找到)
问题描述
所以我一直试图用这个函数从我的表中删除一个人:
const deletePerson = async (id) => {
await fetch(`http://localhost:3000/people/${id}`, {
method: "DELETE",
headers: {
"Content-type": "application/json"
}
})
await setPeople(people.filter(person => person.id !== id))
}
这是表格:
<table>
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Age</th>
<th></th>
</tr>
</thead>
<tbody>
{people.map((person) => (
<tr key={person.id + 1}>
<td>{person.id}</td>
<td>{person.name}</td>
<td>{person.age}</td>
<td>
<button onClick={deletePerson} id="remove-button">REMOVE</button>
</td>
</tr>
))}
</tbody>
</table>
这是json文件(我使用mock db,JSON服务器):
{
"people": [
{
"name": "John Doe",
"age": "69",
"id": 1
},
{
"name": "Jane Doe",
"age": "64",
"id": 2
}
]
}
当我单击删除按钮时,删除功能无法识别 id(我猜)并且出现此错误。我一直在尝试自己解决它,但我无法成功。我是 ajax 和 http 请求的新手,所以我愿意接受建议和信息。
解决方案
您正在传递整个person
对象,而您只需要 ID。要么只传递 ID,要么修改你的deletePerson
来处理person
对象:
const deletePerson = async (person) => {
await fetch(`http://localhost:3000/people/${person.id}`, {
method: "DELETE",
headers: {
"Content-type": "application/json"
}
})
await setPeople(people.filter(_person => _person.id !== person.id))
}
推荐阅读
- python - ValueError: 层序贯_10 的输入 0 与层不兼容:预期 ndim=5,发现 ndim=4。Alexnet(cnn) + LSTM
- java - 是否可以使用 Java 下载整个 YouTube 播放列表,更具体地说是 Android Studio
- java - 如何在 Java 中禁用 linting?
- ruby-on-rails - Rspec ArgumentError:参数数量错误(给定 2,预期为 0)
- laravel - 如何在 Laravel 中获取分页查询的总和
- arrays - 算法:是否可以扫描(迭代行、列、对角线和反向对角线)一个简单的数组?
- c# - 如何使用互操作或打开 xml sdk c#为幻灯片添加过渡到 powerpoint
- laravel - Laravel 8:预期响应代码 220,但得到代码“500”
- javascript - mongodb-topology-manager 不保存我的数据
- validation - 无法覆盖 Nestjs ValidationPipe 的 exceptionFactory 属性