Итак, у меня есть простое React CRUD приложение, которое имеет Node / Express бэкэнд и использует MongoDB для базы данных. Я могу сделать свой запрос GET
, используя fetch , который отображает все мои данные из бэкэнда. И я могу создать новую запись в своей базе данных, используя POST
, но я не могу PUT
и DELETE
.
Сначала вот мой контроллер и маршруты из бэкэнда.
/*
controllers
*/
const updateStudent = (req, res) => {
// Validate Request
if (!req.body.email) {
return res.status(400).send({
message: "This student is not enrolled",
});
}
Student.findByIdAndUpdate(
req.params.id, {
$set: req.body,
}, {
new: true
}
)
.then((student) => {
if (!student) {
return res.status(404).send({
message: "Student not found with Student ID " + req.params.studentId,
});
}
res.send(student);
})
.catch((err) => {
if (err.kind === "ObjectId") {
return res.status(404).send({
message: "Student not found with Student ID " + req.params.studentId,
});
}
return res.status(500).send({
message: "Error updating note with Student ID " + req.params.studentId,
});
});
};
const deleteStudent = (req, res) => {
Student.findByIdAndRemove(req.params.id, function(err) {
if (err) return next(err);
res.send("Deleted successfully!");
});
};
/*
routes
*/
router.put("/students/:id", updateStudent);
router.delete("/students/:id", deleteStudent);
Теперь я проверил это в Postman
, и оно работает.
вот данные, которые я получаю:
[{
"_id": "5ea5b23f16d306c66835d470",
"fname": "John",
"lname": "Doe",
"email": "johndoe@doe.com",
"phone": "123-789-0456",
"studentId": "aiw3sgspj",
"street1": "1001 Doe St",
"street2": "Apt. 105",
"city": "Washington",
"state": "DC",
"zip": 20010,
"createdAt": "2020-04-26T16:09:35.641Z",
"updatedAt": "2020-04-26T16:09:35.641Z"
},
{
"_id": "5ea5b27116d306c66835d471",
"fname": "Jane",
"lname": "Did",
"email": "johndoe@did.com",
"phone": "789-123-4560",
"studentId": "n5bsm5mzx",
"street1": "1001 Did St",
"street2": "Apt. 105",
"city": "Washington",
"state": "DC",
"zip": 20010,
"createdAt": "2020-04-26T16:10:25.050Z",
"updatedAt": "2020-04-26T16:10:25.050Z"
},
{
"_id": "5ea5b2b016d306c66835d472",
"fname": "Jim",
"lname": "Done",
"email": "jdone@done.com",
"phone": "456-789-0231",
"studentId": "h7ofl7eue",
"street1": "1001 Done St",
"street2": "Apt. 105",
"city": "Washington",
"state": "DC",
"zip": 20010,
"createdAt": "2020-04-26T16:11:28.797Z",
"updatedAt": "2020-04-26T16:11:28.797Z"
},
{
"_id": "5ea5b2d916d306c66835d473",
"fname": "Jll",
"lname": "Do",
"email": "jdo@do.com",
"phone": "123-456-7890",
"studentId": "goentqjix",
"street1": "1001 Do St",
"street2": "Apt. 105",
"city": "Washington",
"state": "DC",
"zip": 20010,
"createdAt": "2020-04-26T16:12:09.236Z",
"updatedAt": "2020-04-26T16:12:09.236Z"
},
{
"_id": "5ea5b7b8d78372d84f0e54f7",
"fname": "Joe",
"lname": "Dare",
"email": "joedare@dare.com",
"phone": "456-234-6789",
"studentId": "x6kj7w05-",
"street1": "1001 Dare St.",
"street2": "Apt. 106",
"city": "Washington",
"state": "DC",
"zip": 20010,
"createdAt": "2020-04-26T16:32:56.465Z",
"updatedAt": "2020-04-26T16:32:56.465Z"
}
]
Здесь вызывается мое обновление в моем приложении React
submitFormEdit = (e) => {
e.preventDefault();
fetch(`http://localhost:8096/api/students/`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
id: this.state.id,
fname: this.state.fname,
lname: this.state.lname,
email: this.state.email,
phone: this.state.phone,
street1: this.state.street1,
street2: this.state.street2,
city: this.state.city,
state: this.state.state,
zip: this.state.zip,
gpa: this.state.gpa,
}),
})
.then((response) => response.json())
.then((item) => {
if (Array.isArray(item)) {
// console.log(item[0])
this.props.updateState(item[0]);
this.props.toggle();
} else {
console.log("failure");
}
})
.catch((err) => console.log(err));
};
и вот мой звонок на удаление
deleteItem = (id) => {
let confirmDelete = window.confirm("Delete item forever?");
if (confirmDelete) {
fetch("http://localhost:8096/api/students", {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
id,
}),
})
.then((response) => response.json())
.then((item) => {
this.props.deleteItemFromState(id);
})
.catch((err) => console.log(err));
}
};