NodeJS 错误:无法从/blog/[id]收集页面数据

2ic8powd  于 2023-03-22  发布在  Node.js
关注(0)|答案(1)|浏览(121)
const Details = ({ userData }) => {
  return (
    <Layout>
      <h1>{userData?.header}</h1>
    </Layout>
   )
}

export default Details

 
export const getStaticPaths = async () =>{
  const res = await fetch(`http://localhost:3000/api/blogs`);
  const blogs = await res.json();
  const ids = blogs.map((blog) => blog.id);
  const paths = ids.map((id)=> ({params:{id: id.toString()}}));

  return{
    paths,
    fallback:false,
  };
};

export const getStaticProps = async (context) =>{
  const res = await fetch(`http://localhost:3000/api/blogs/${context.params.id}`);
  const userData = await res.json();

  return{
    props:{
      data,
      userData,
    }
  }
}

npm run build我的Next.js项目时,我在控制台中得到这样一个错误:

Error: Failed to collect page data from /blog/[id]

为什么会发生这种情况?

iszxjhcz

iszxjhcz1#

因为你没有从任何API获取任何东西,所以你不需要远程获取任何东西,这就是为什么你会得到一个ECONNREFUSED错误。

更新

我在您的/blog/*文件夹中发现两个错误:

  • /blog/[id].js的第106行添加- 1(见下文)
  • 删除/blog/index.js的第131和132行
    /博客/[ID].js
import { data } from "../../data.js";

const Details = ({ userData }) => {
  return <Layout>{/* ... */}</Layout>;
};

export default Details;

export const getStaticPaths = async () => {
  const ids = data.map(({ id }) => id);
  const paths = ids.map((id) => ({ params: { id: id.toString() } }));
  return {
    paths,
    fallback: false,
  };
};

export const getStaticProps = async (context) => {
  // You where trying here to get posts by id:
  // 1, 2, 3, 4
  // But what you really want is to get array indexes:
  // 0, 1, 2, 3
  // that's why we are adding - 1
  const userData = data[context.params.id - 1]; // <----- add - 1

  return {
    props: {
      data,
      userData,
    },
  };
};

/博客/索引.js

export const getStaticProps = async (context) => {
  // ----- remove the fetch -----

  return {
    props: {
      data,
    },
  };
};

相关问题