You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中getStaticProps获取数据后props返回undefined求助

Next.js getStaticProps返回props为undefined的解决方法

以下是针对你代码问题的排查和修复方案:

1. 修复getAllBooks的错误处理与数据校验

你的getAllBooks存在两个问题:一是请求失败时返回Error对象,会导致getStaticProps无法拿到有效数据;二是未校验res.data.books是否存在,若接口返回结构不符,会直接返回undefined。

修改后的代码:

export const getAllBooks = async() => {
  try {
    // 移除无效的前端CORS头,该头由后端设置
    const res = await axios.get("http://localhost:3000/api/v1/books");
    if (res.status !== 200) {
      throw new Error("Internal Server error");
    }
    // 打印接口返回数据,确认结构是否包含books字段
    console.log('API返回数据:', res.data);
    // 兜底处理,避免books字段不存在时返回undefined
    return res.data.books || [];
  } catch (error) {
    console.error('获取书籍数据失败:', error);
    // 错误场景返回空数组,保证props始终有值
    return [];
  }
}

2. 给getStaticProps添加日志排查

在getStaticProps中打印获取到的books值,确认数据是否正常传入:

export const getStaticProps = async () => {
  const books = await getAllBooks();
  console.log('getStaticProps拿到的books:', books);
  return { props: { books } };
}

3. 解决CORS问题

前端请求中设置Access-Control-Allow-Origin无效,该响应头需由后端接口配置。本地开发时,可通过Next.js代理避免CORS错误:
在next.config.js中添加代理配置:

module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/v1/books',
        destination: 'http://localhost:3000/api/v1/books',
      },
    ];
  },
};

随后将请求地址改为/api/v1/books即可。

4. 确认getStaticProps的执行逻辑

getStaticProps在生产环境仅构建时执行,若需实时获取数据,建议改用getServerSideProps或在组件内通过useEffect发起客户端请求。

内容的提问来源于stack exchange,提问作者Maksym Yuzva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 14:20:19