0

so when you click on a post, it redirects you to the post page, it works on load, but shows 404 on refresh. this is the code of the postpage:

import { useEffect, useState } from "react";
import { useRouter } from "next/router";

export default function PostPage( ) {
  const [postInfo, setPostInfo] = useState(null);
  const router = useRouter();
  const { id } = router.query;

  useEffect(() => {
    fetch(`http://localhost:4000/post/${id}`).then((response) => {
      response.json().then((postInfo) => {
        setPostInfo(postInfo);
        // console.log(postInfo);
      });
    });
  }, [id]);

  return (
    <>
      <div>post page here</div>
    </>
  );
}

i've tried nextjs serversideprops, getStaticPath, getStaticProps nothing works, just help me see what i can do. this is the code of the post js that redirects you to the post page on click:

import { formatISO9075 } from "date-fns";
import Link from "next/link";

/* eslint-disable @next/next/no-img-element */
export default function Post({
  _id,
  title,
  summary,
  cover,
  content,
  createdAt,
  author,
}) {
  return (
    <>
      <div className="post">
        <div className="image">
          <Link as={`/post/${_id}`} href={`/PostPage?id=${_id}`}>
            <img
              src={"http://localhost:4000/" + cover}
              alt="image of the post"
            />
          </Link>
        </div>

        <div className="texts">
        <Link as={`/post/${_id}`} href={`/PostPage?id=${_id}`}>
            <h2>{title}</h2>
          </Link>

          <p className="info">
            <a className="author">{author.username}</a>
            <time>{formatISO9075(new Date(createdAt))}</time>
          </p>
          <p className="summary">{summary}</p>
        </div>
      </div>
    </>
  );
}

and this is part of the routing in express:

app.get("/post", async (req, res) => {
  res.json(
    await Post.find()
    .populate("author", ["username"])
    .sort({ createdAt: -1 })
    .limit(20)
    );
});

app.get("/post/:id", async (req, res) => {
  const {id} = req.params;
  const postDoc = await Post.findById(id).populate("author", ["username"]); // only get username, not with password
  res.json(postDoc);
}); //get a single post

app.listen(4000);

tunji
  • 13
  • 3

0 Answers0