简体   繁体   中英

How to pass users' data from nodeJS to reactJS using Express/Mysql

I need to pass author's email in my posts. I though I can do it by joining tables in my posts route, but it doesn't really work.

Here is my route:

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

Here is code with my axios fetching the route:

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

And this is how I tried to return it:

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

                      Author:<br></br>
                      <small>{post.user_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>

Everything works except the fetching Author.

a typo its user_email not users_email your sending email in the value assingned to user_email and in front end using users_email

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