如何让更新和删除端点在我的React应用程序中正常工作



所以我有一个简单的React CRUD应用程序,它有一个Node/Express后端,并将MongoDB用于数据库。我可以使用fetch发出GET请求,该请求显示来自后端的所有数据。我可以使用POST在数据库中创建新记录,但不能使用PUTDELETE

首先是我的控制器和来自后端的路由。

/*
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));
}
};

请将fetch方法更改为大写,这可能对您有用。方法:"delete",应替换为方法:"delete",put也是如此。

React代码中的请求url格式不正确,应该是

fetch("http://localhost:8096/api/students/"+id

因为您正在从node.js中的req.params.id访问id,所以不要将其放在主体中

因此删除代码应该如下所示:

deleteItem = (id) => {
let confirmDelete = window.confirm("Delete item forever?");
if (confirmDelete) {
fetch(`http://localhost:8096/api/students/${id}`, {
method: "DELETE",
})
.then((response) => response.json())
.then(() => {
this.props.deleteItemFromState(id);
})
.catch((err) => console.log(err));
}
};

我从承诺中删除了参数,并将id添加到端点

更新代码应该看起来像这个

submitFormEdit = (e) => {
e.preventDefault();
const {
item
} = this.props;
fetch(`http://localhost:8096/api/students/${item._id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(this.state),
})
.then((response) => response.json())
.then((item) => {
if (item) {
this.props.updateState(item);
this.props.toggle();
} else {
console.log("failure");
}
})
.catch((err) => console.log(err));
};

Array.isArray(item)不正确,因为我不是在更新数组,而是在更新对象

最新更新