【发布时间】:2020-03-26 03:59:18
【问题描述】:
我正在学习 REST API。我正在将 react 应用程序用于 Node js 和 express 服务器的前端和后端。对于 API,我使用的是 REST API。我正在使用 MongoDB 作为数据库。我成功地将所有数据显示到浏览器。我可以搜索数据。现在我想删除数据。我不知道如何从 REST API 端点删除数据。如果有人帮助我,我会非常高兴。我使用 Postman 测试了我的后端。一切都按预期正常工作。
这是我的后端删除终点
app.delete("/students/:id", async (req, res, next) => {
const id = req.params.id;
try {
student
.remove({ _id: id })
.exec()
.then(data => {
res.json(data);
});
} catch (error) {
console.log(error);
}
});
我将我的 API END 点导出到 React js
export async function deleteStudent(id) {
const response = await fetch(`/students/${id}`, {
method: "DELETE"
});
return response.json();
}
这是我要删除数据的主要组件
import React, { useState, useEffect } from "react";
import { logEntry } from "../Api/Api";
import { deleteStudent } from "../Api/Api";
function Datatable() {
const [total, settotal] = useState([]);
const [searchItem, setsearchItem] = useState({
item: ""
});
const [data, setdata] = useState([]);
const handleChange = e => {
setsearchItem({ item: e.target.value });
};
const getEntries = async () => {
const logEntries = await logEntry();
console.log(logEntries);
settotal(logEntries.count);
setdata(logEntries.students);
};
const nameFilter = data.filter(list => {
return list.name.toLowerCase().includes(searchItem.item.toLowerCase());
});
const deleteData = async id => {
await deleteStudent(id);
};
useEffect(() => {
getEntries();
}, []);
return (
<div>
<div style={{ paddingLeft: "800px" }}>
<input
placeholder="Search student"
onChange={handleChange}
style={{ width: "200px", height: "30px" }}
/>
</div>
<p>Total student: {total} </p>
<table>
<thead>
<tr>
<th>Name</th>
<th>City</th>
<th>Address</th>
<th>Phone</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{nameFilter === "" ? (
<p>Student not found</p>
) : (
nameFilter.map(list => {
return (
<tr>
<td>{list.name}</td>
<td>{list.city}</td>
<td>{list.address}</td>
<td>{list.phone}</td>
<td>{list.email}</td>
<td>
<a
className="waves-effect red btn-small"
onClick={() => deleteData(list.id)}
>
Delete
</a>
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
);
}
export default Datatable;
我不知道,我在做什么?
【问题讨论】: