错误:在以下路径上遇到导出错误:“/”。尝试部署Next.JS项目。

huangapple go评论87阅读模式
英文:

Error: Export encountered errors on following paths: "/". When trying to deploy Next.JS project

问题

I am trying to deploy my nextJS project, however, the console keeps returning this error:

Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at parseJSONFromBytes (node:internal/deps/undici/undici:6498:19)
    at successSteps (node:internal/deps/undici/undici:6472:27)
    at node:internal/deps/undici/undici:1145:60
    at node:internal/process/task_queues:140:7
    at AsyncResource.runInAsyncScope (node:async_hooks:204:9)
    at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
info  - Generating static pages (4/4)

> Build error occurred
Error: Export encountered errors on the following paths:
    /
    at /vercel/path0/node_modules/next/dist/export/index.js:425:19
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:79:20)
    at async /vercel/path0/node_modules/next/dist/build/index.js:1422:21
    at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:79:20)
    at async /vercel/path0/node_modules/next/dist/build/index.js:1280:17
    at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:79:20)
    at async Object.build [as default] (/vercel/path0/node_modules/next/dist/build/index.js:73:29)
Error: Command "npm run build" exited with 1
BUILD_UTILS_SPAWN_1: Command "npm run build" exited with 1

When I try to build it locally on my terminal, I also get a very similar error (using "npm run build"):

Error: Export encountered errors on the following paths:
    /
    at /Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/export/index.js:425:19
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Span.traceAsyncFn (/Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/trace/trace.js:79:20)
    at async /Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/build/index.js:1422:21
    at async Span.traceAsyncFn (/Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/trace/trace.js:79:20)
    at async /Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/build/index.js:1280:17
    at async Span.traceAsyncFn (/Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/trace/trace.js:79:20)
    at async Object.build [as default] (/Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/build/index.js:73:29)

I've tried looking at the Next.js prerender error page, but I haven't had any luck with the tips provided there. I'm still relatively new to Next.js and decided to learn through it.

I am using a "getStaticProps," but I'm not sure if that's what the problem is. This is my code in index.tsx:

export const getStaticProps: GetStaticProps<Props> = async () => {
  const pageInfo = await fetchPageInfo();
  const experiences = await fetchExperiences();
  const projects = await fetchProjects();
  const skills = await fetchSkills();
  const socials = await fetchSocials();

  return {
    props: {
      pageInfo,
      experiences,
      projects,
      skills,
      socials,
    },

    // Next.js will attempt to re-generate the page:
    // - When a request comes in
    // - At most once every day
    revalidate: 86400, // In seconds
  };
};

Looking at the error, it doesn't specify a specific page is erroring out, only "/" which leads me to believe it is a problem in my index file.

Here is an example of my code to fetch the API request in utils/fetchProject.ts:

import { Project } from "@/typings";

export const fetchProjects = async () => {
  const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getProject`);

  const data = await res.json();
  const projects: Project[] = data.projects;

  return projects;
};

Here is an example of my code to get the API response in pages/api/getProject.ts:

import { sanityClient } from "../../sanity";
import { Project } from "../../typings";

const query = groq`
  *[_type == "project" ] {
    ...,
    technologies[]->
  }
`;

type Data = {
  projects: Project[];
};

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  const projects: Project[] = await sanityClient.fetch(query);
  res.status(200).json({ projects });
}

I've been following this YouTube video as a walkthrough: YouTube Video Link.

英文:

I am trying to deploy my nextJS project however the console keeps returning this error

Error occurred prerendering page &quot;/&quot;. Read more: https://nextjs.org/docs/messages/prerender-error
SyntaxError: Unexpected token &lt; in JSON at position 0
    at JSON.parse (&lt;anonymous&gt;)
    at parseJSONFromBytes (node:internal/deps/undici/undici:6498:19)
    at successSteps (node:internal/deps/undici/undici:6472:27)
    at node:internal/deps/undici/undici:1145:60
    at node:internal/process/task_queues:140:7
    at AsyncResource.runInAsyncScope (node:async_hooks:204:9)
    at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
info  - Generating static pages (4/4)

&gt; Build error occurred
Error: Export encountered errors on following paths:
	/
    at /vercel/path0/node_modules/next/dist/export/index.js:425:19
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:79:20)
    at async /vercel/path0/node_modules/next/dist/build/index.js:1422:21
    at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:79:20)
    at async /vercel/path0/node_modules/next/dist/build/index.js:1280:17
    at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:79:20)
    at async Object.build [as default] (/vercel/path0/node_modules/next/dist/build/index.js:73:29)
Error: Command &quot;npm run build&quot; exited with 1
BUILD_UTILS_SPAWN_1: Command &quot;npm run build&quot; exited with 1

When I try to build it locally on my terminal I also get a very similar error (using "npm run build")

Error: Export encountered errors on following paths:
        /
    at /Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/export/index.js:425:19
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Span.traceAsyncFn (/Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/trace/trace.js:79:20)
    at async /Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/build/index.js:1422:21
    at async Span.traceAsyncFn (/Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/trace/trace.js:79:20)
    at async /Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/build/index.js:1280:17
    at async Span.traceAsyncFn (/Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/trace/trace.js:79:20)
    at async Object.build [as default] (/Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/build/index.js:73:29)

I've tried looking at NextJS prerender error page but I haven't gotten any luck with the tips through there. I'm still pretty new to Next and decided to learn through it.

I am using a "getStaticProps" but I'm not sure if thats what the problem is. This is my code in index.tsx

export const getStaticProps: GetStaticProps&lt;Props&gt; = async () =&gt; {
  const pageInfo = await fetchPageInfo();
  const experiences = await fetchExperiences();
  const projects = await fetchProjects();
  const skills = await fetchSkills();
  const socials = await fetchSocials();

  return {
    props: {
      pageInfo,
      experiences,
      projects,
      skills,
      socials,
    },

    // Next.js will attempt to re-generate the page:
    // - When a request comes in
    // - At most once every day
    revalidate: 86400, // In seconds
  };
};

Looking at the error it doesn't say a specific page is erroring out, only "/" which leads me to believe it is a problem in my index file.

Here is an example of my code to fetch the api request in utils/fetchProject.ts

import { Project } from &quot;@/typings&quot;;

export const fetchProjects = async () =&gt; {
  const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getProject`);

  const data = await res.json();
  const projects: Project[] = data.projects;

  return projects;
};

Here is an example of my code to get the api response in pages/api/getProject.ts

import { sanityClient } from &quot;../../sanity&quot;;
import { Project } from &quot;../../typings&quot;;

const query = groq`
  *[_type == &quot;project&quot; ] {
    ...,
    technologies[]-&gt;
  }
`;

type Data = {
  projects: Project[];
};

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse&lt;Data&gt;
) {
  const projects: Project[] = await sanityClient.fetch(query);
  res.status(200).json({ projects });
}

I've been following this youtube video as a walkthrough.

答案1

得分: 1

以下是已翻译的部分:

从您分享的错误消息来看,似乎主要问题与解析JSON数据有关。错误消息说:JSON中位置0处的意外令牌&lt;。通常,当您期望从服务器获取JSON响应,而实际上收到的是HTML时,就会发生这种错误。&lt;字符是HTML文档的典型起始字符。

当服务器发送错误页面(通常为HTML格式)而不是您期望的JSON数据时,可能会发生这种情况。

查看您的代码,您在getStaticProps中进行了fetch请求。错误可能发生在这些fetch请求中的一个,特别是在调用res.json()方法来解析JSON数据时。

要解决此问题,我建议执行以下步骤:

  1. 检查API是否正常运行:在浏览器中访问URL以查看它们是否按预期运行。

  2. 在解析之前检查响应:在fetchProjects函数中添加一个检查,以查看来自服务器的响应是否正常,然后再将响应解析为JSON。

以下是如何修改fetchProjects的方法:

export const fetchProjects = async () => {
  const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getProject`);

  // 检查响应是否成功
  if (!res.ok) {
    throw new Error(`服务器响应状态: ${res.status}`);
  }

  const data = await res.json();
  const projects: Project[] = data.projects;

  return projects;
};

在此代码中,res.ok在响应状态在200-299范围内时为true。如果超出此范围,这意味着发生了服务器错误,您可能收到了预期的JSON数据而不是HTML错误页面。

添加此检查并抛出错误可让您查看状态代码,这可能提供关于出现问题的线索。

  1. 检查您的响应:如果错误仍然存在,可以在res.json()之前添加console.log(res)console.log(await res.text()),以打印出从服务器接收的内容。

  2. 检查您的服务器代码:确保您的位于/api/getProject的服务器正确处理错误并始终以JSON格式响应。

您应该在服务器代码中添加try/catch块以处理可能发生的任何错误,并以JSON格式响应错误,而不是让服务器默认发送HTML错误页面。

以下是包含错误处理的handler函数的修改版本:

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  try {
    const projects: Project[] = await sanityClient.fetch(query);
    res.status(200).json({ projects });
  } catch (error) {
    console.error('获取项目时出错:', error);
    res.status(500).json({ error: '获取项目时出错' });
  }
}

通过执行这些检查,您应该能够缩小错误来源并进行修复。

英文:

From the error message you've shared, it seems that the main issue is related to parsing JSON data. The error message says: Unexpected token &lt; in JSON at position 0. This error usually occurs when you're expecting a JSON response from a server and you're instead receiving HTML. The &lt; character is a typical start character for an HTML document.

This may happen when the server sends an error page (which is often in HTML format) instead of the JSON data you're expecting.

Looking at your code, you're making fetch requests in your getStaticProps. The error likely occurs in one of these fetch requests, in particular, when you call the res.json() method to parse the JSON data.

To solve this issue, I recommend the following steps:

  1. Check if the APIs are up and running: Visit the URLs in the browser to see if they are working as expected.

  2. Check the response before parsing it: Add a check in your fetchProjects function to see if the response from the server is okay before parsing the response as JSON.

Here's how you could modify fetchProjects:

export const fetchProjects = async () =&gt; {
  const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getProject`);

  // check if the response was successful
  if (!res.ok) {
    throw new Error(`Server responded with status: ${res.status}`);
  }

  const data = await res.json();
  const projects: Project[] = data.projects;

  return projects;
};

In this code, res.ok is true if the response status is in the range 200-299. If it's outside this range, it means that there was a server error, and you probably received an HTML error page instead of the expected JSON data.

Adding the check and throwing an error allows you to see what the status code was, which might provide a clue about what went wrong.

  1. Inspect your response: If the error persists, add console.log(res) or console.log(await res.text()) before the res.json() line to print out what you're receiving from the server.

  2. Check your server code: Ensure your server at /api/getProject is correctly handling errors and always responding with JSON.

You should add try/catch blocks in your server code to handle any errors that might occur and respond with an error in JSON format, rather than letting the server default to sending an HTML error page.

Here is a modified version of your handler function that includes error handling:

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse&lt;Data&gt;
) {
  try {
    const projects: Project[] = await sanityClient.fetch(query);
    res.status(200).json({ projects });
  } catch (error) {
    console.error(&#39;Error fetching projects:&#39;, error);
    res.status(500).json({ error: &#39;An error occurred fetching projects&#39; });
  }
}

With these checks, you should be able to narrow down where the error is coming from and fix it.

答案2

得分: 0

已通过首先部署网站的静态版本来解决此问题。然后,在部署后,将URL输入到Vercel项目中的环境变量中。我怀疑错误发生在utils/fetchProject.ts(以及其他API响应助手)中,因为它找不到从URL获取API响应的链接。

英文:

Fixed it by deploying a static version of the site first. Then after deploying, inputting the url into the environment variables in the vercel project. I suspect the error was happening in the utils/fetchProject.ts (and other api response helpers) because it couldn't find the link to actually fetch the api response from the url

huangapple
  • 本文由 发表于 2023年6月12日 09:44:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76453219.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定