首页 > 解决方案 > Vercel Next.js 简单 Next.js 代码的构建错误

问题描述

我创建了一个简单的 Next.js 代码,它在本地运行良好,但在 Vercel 上部署时出现错误:

  1. 使用 npx create-next-app 创建一个新的 Next.js 应用程序。当前版本是 11.1.0

  2. 在 pages/index.js 添加 getStaticProps 函数,从 pages/api/hello 获取数据(create-next-app 创建的默认文件)

    从“配置”导入 { API_URL };... export const getStaticProps = async () => { const res = await fetch( ${API_URL}/api/hello); 常量数据 = 等待 res.json();

    返回{道具:{数据,重新验证:1,},};};

  3. 在根目录下创建 config/index.js 并写在那里

    导出常量 API_URL = process.env.NEXT_PUBLIC_VERCEL_URL || 'http://localhost:3000';

  4. 完整版可在 https://github.com/RayaLevinson/next_js_test

  5. 本地(使用 npm run dev)工作正常。

  6. 在 Vercel.7 上部署。出现构建错误:预渲染页面“/”时发生错误。阅读更多:https ://nextjs.org/docs/messages/prerender-error

    TypeError:仅支持绝对 URL

     at getNodeRequestOptions (/vercel/path0/node_modules/node-fetch/lib/index.js:1305:9)
    
     at /vercel/path0/node_modules/node-fetch/lib/index.js:1410:19
     at new Promise (<anonymous>)
    
     at Function.fetch [as default] (/vercel/path0/node_modules/node-fetch/lib/index.js:1407:9)
     at fetchWithAgent (/vercel/path0/node_modules/next/dist/server/node-polyfill-fetch.js:38:39)
    

    在 getStaticProps (/vercel/path0/.next/server/pages/index.js:60:21) 在 renderToHTML (/vercel/path0/node_modules/next/dist/server/render.js:329:30) 在异步 / vercel/path0/node_modules/next/dist/export/worker.js:273:36 在异步 Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/telemetry/trace/trace.js:60:20)

标签: deploymentnext.jsvercel

解决方案


推荐阅读