简体   繁体   中英

How to get multi id by axios in reactjs?

I am stuck on how to get 2 ids by Axios in react js, I can handle the server-side, but on the client-side, I don't know how to get it. here is my server-side code:

I have posts/blogs that people also can leave a comment on. so the id of the comments count by the id of the posts:

ex:

post with id/80 has many comments I wanna update comments with their id: it could be like this: 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);
});

so this is the client-side code:

  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,
});
};

when I test it with postman I used this URL: http://localhost:3007/comments/88/141 it just worked as I expected.

and this is the put method:

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

};

any suggestions appreciated:

when you do this in the controller, you are reading post data (body) :

const { newCommentBody, postId, id } = req.body;

when you do this you are not pushing post data either, the ids are route parameters :

const response = await axios.put(
  `http://localhost:3007/comments/123/234`,
  {
    headers: { accessToken: localStorage.getItem("accessToken") },
  }
);

change the controller to this :

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM