提问者:小点点

如何使用Express/MySQL将用户数据从nodeJS传递到reactJS


我需要在我的帖子中传递作者的电子邮件。 我想我可以通过在我的帖子路线中加入表来实现,但它并不真正起作用。

这是我的路线:

router.get("/posts", async (req, res) => {
  const { id } = req.session.user;
  //const usersPosts = await user.$relatedQuery("posts");
  try {
    const user = await User.query().findById(id);
    if (!user) {
      return res.status(401).send("User was not found");
    }
    const posts = await Post.query()
      .select([
        "users.email",
        "images.name",
        "posts.category",
        "posts.title",
        "posts.description",
        "posts.created_at"
      ])
      .join("images", { "posts.image_id": "images.id" });
      .join("users", { "posts.user_email": "users.email" });

    console.log("it worked");
    return res.status(200).send({ posts: posts });
  } catch (error) {
    console.log(error);
    return res.status(404).send({ response: "No posts found" });
  }
});

下面是我的axios获取路由的代码:

function Home(props) {
  const [posts, setPosts] = useState([]);

  const getPosts = async () => {
    try {
      let response = await axios.get("http://localhost:9090/posts", {
        withCredentials: true
      });

      console.log(response.data.posts);
      setPosts(response.data.posts);
    } catch (error) {
      console.log(error.data);
    }
  };
  useEffect(() => {
    getPosts();
  }, []);

这就是我试图归还它的方式:

{posts.map((post, index) => {
          return (
            <>

                      Author:<br></br>
                      <small>{post.users_email}</small>
                    </p>
                    <p>
                      Category:<br></br>
                      <small>{post.category}</small>
                    </p>

                    <p>
                      Description:<br></br>
                      <small>{post.description}</small>
                    </p>
                    <p>
                      Created: <br></br>
                      <small>{post.created_at}</small>

除了抓取的作者之外,所有的东西都能工作。


共1个答案

匿名用户

输入user_email而不是users_email您发送电子邮件的值,并且在前端使用users_email