简体   繁体   English

next.js 语法错误:JSON 中的意外令牌 < position 0

[英]next.js SyntaxError: Unexpected token < in JSON at position 0

API is working, I can use this API on other pages. API 有效,我可以在其他页面上使用这个 API。 but this page can't, I don't know where's wrong??但是这个页面不行,不知道哪里错了?? code:代码:

export async function getStaticPaths() {
  const response = await fetch("http://localhost:8080/students");
  const data = await response.json();

  const paths = data.map((d) => {
    return {
      params: {
        id: d._id.toString(),
      },
    };
  });

  return {
    paths,
    fallback: false,
  };
}

export async function getStaticProps({ params }) {
  const response = await fetch(`http://localhost:8080/students/${params.id}`);
  const data = await response.json();
  return {
    props: {
      data,
      S,
    },
  };
}

export default function StudentProfile({ data }) {
  return (
    <div>
      <h1>{data.name}</h1>
      <h1>{data.age}</h1>
      <h1>{data.id}</h1>
    </div>
  );
}

error message:错误信息:

Server Error SyntaxError: Unexpected token < in JSON at position 0 This error happened while generating the page.服务器错误 SyntaxError: Unexpected token < in JSON at position 0 生成页面时发生此错误。 Any console logs will be displayed in the terminal window. pages/profile/[id].js (26:15) @ async getStaticProps 24 |任何控制台日志都将显示在终端 window 中。 pages/profile/[id].js (26:15) @async getStaticProps 24 | export async function getStaticProps({ params }) { 25 |导出异步 function getStaticProps({ params }) { 25 | const response = await fetch( http://localhost:8080/students/${params.id} ); const response = await fetch( http://localhost:8080/students/${params.id} ); 26 | 26 | const data = await response.json(); const data = await response.json(); | | ^ 27 | ^ 27 | return { 28 |返回 { 28 | props: { 29 |道具:{ 29 | data,数据,

I sure about the API is successfully connected.我确定 API 已成功连接。 This code can run successfully and display data:这段代码可以成功运行并显示数据:

export async function getStaticProps() {
  const respone = await fetch("http://localhost:8080/students");
  const data = await respone.json();
  return {
    props: {
      data,
    },
  };
}

export default function StaticGenerationPage({ data }) {
  return (
    <div>
      {data.map((d) => {
        return <h1>{d.name + " " + d._id}</h1>;
      })}
    </div>
  );
}

Are there any other potential causes of error?还有其他潜在的错误原因吗?

Unexpected token < in JSON at position 0 means the JSON returned by the API is not valid Unexpected token < in JSON at position 0表示 API 返回的 JSON 无效

Also, getStaticProps does not have access to the incoming request (such as query parameters or HTTP headers) see getStaticProps docs .此外, getStaticProps无权访问传入请求(例如查询参数或 HTTP 标头),请参阅getStaticProps 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM