![](/img/trans.png)
[英]How to get ID from a input field and DELETE by that ID in ReactJS and Axios
[英]How to get multi id by axios in reactjs?
我被困在如何通过 Axios 在 react js 中获取 2 个 id,我可以处理服务器端,但是在客户端,我不知道如何获取它。 这是我的服务器端代码:
我有帖子/博客,人们也可以发表评论。 所以评论的 id 按帖子的 id 计算:
前任:
带有 id/80 的帖子有很多评论我想用他们的 ID 更新评论:可能是这样的:posts/80/120
router.put("/:postId/:id", validateToken, async (req, res) => {
const { newCommentBody, postId, id } = req.body;
console.log("body", req.body);
await Comments.update(
{ commentBody: newCommentBody },
{ where: { id: id } }
);
console.log("postId in comment", id)
res.json("comment updated successfully!", newCommentBody, postId, id);
});
所以这是客户端代码:
const updateTheComment = async (postId, id) => {
const response = await axios.get(
`http://localhost:3007/comments/${id}`,
{
headers: { accessToken: localStorage.getItem("accessToken") },
}
);
console.log('getting commentBody data', response.data.commentBody)
setCommentObject({
commentBody: response.data.commentBody,
});
};
当我用邮递员测试它时,我使用了这个 URL: http://localhost:3007/comments/88/141它就像我预期的那样工作。
这是 put 方法:
const subNewComment = (e, postId) => {
e.preventDefault();
axios
.put(
`http://localhost:3007/comments/${postId}/${id}`,
{
newCommentBody: commentObject.commentBody,
id: id,
},
{
headers: {
accessToken: localStorage.getItem("accessToken"),
},
}
)
.then((res) => {
if (res.data.error) {
alert(res.data.error);
} else {
history.push("/");
}
});
};
任何建议表示赞赏:
当您在控制器中执行此操作时,您正在阅读帖子数据(正文):
const { newCommentBody, postId, id } = req.body;
当您这样做时,您也不会推送发布数据,ID 是路由参数:
const response = await axios.put(
`http://localhost:3007/comments/123/234`,
{
headers: { accessToken: localStorage.getItem("accessToken") },
}
);
将控制器更改为:
router.put("/:postId/:id", validateToken, async (req, res) => {
const { newCommentBody } = req.body;
const { postId, id } = req.params;
console.log("body", req.body);
console.log("params", req.params);
...
你的网址不完整,只是给它加上posId, http://localhost:3007/comments/${postId}/${id}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.