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

未修改代码却突发SyntaxError: Unexpected token < in JSON at position 0错误

输入图片描述

我正在开发Airbnb克隆项目,今早还能正常通过npm run dev启动本地服务器,没改任何代码现在却启动失败。查资料说可能是接口返回HTML而非JSON,但不知道为啥突然这样。项目已经部署可以访问,求指导修复。

涉及代码

import Head from 'next/head'
import Image from 'next/image'
import Header from '../Components/Header.js'
import Banner from '../Components/Banner.js'
import styles from '../styles/Home.module.css'
import SmallCard from '../Components/SmallCard.js'
import MediumCard from '../Components/MediumCard.js'
import LargeCard from '../Components/LargeCard.js'
import Footer from '../Components/Footer.js'

export default function Home({exploreData, cardsData}) {
  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <Header />
      <Banner />
      <main className='max-w-6xl mx-auto px-12 sm:px-16'>
        <section className='pt-6'>
          <h2 className='text-4xl font-semibold pb-5'>Explore Nearby</h2>
          
          {/* Pull name from a server - API endpoints */}
          <div className='grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 '>
            {exploreData?.map(({img, distance, location}) => (
              <SmallCard
                key={img} 
                img={img} 
                distance={distance} 
                location={location}  
              />
            ))}
          </div>
        </section>

        <section>
          <h2 className='text-4xl font-semibold py-8'>Live Anywhere</h2>
          {/* pull data from API endpoints */}
          <div className='flex space-x-3 overflow-scroll scrollbar-hide p-3 -ml-3'>
            {cardsData?.map(({ img, title }) => (
              <MediumCard
              key={img}
              img={img}
              title={title}
              />
            ))}
          </div>
        </section>

        <section>
          <LargeCard
            img="https://links.papareact.com/4cj"
            title="The Greatest Outdoors"
            description="Wishlist curated by Airbnb"
            buttonText="Get Inspired"
          />
        </section>
      </main>

      <Footer />
    </div>
  )
}

export async function getStaticProps() {
  const exploreData = await fetch('https://links.papareact.com/pyp')
  .then (
    (res) => res.json()
  );

  const cardsData = await fetch('https://links.papareact.com/zp1')
  .then (
    (res) => res.json()
  );
  
  return{
    props: {
      exploreData,
      cardsData,
    },
  };
}

问题定位与修复方案

  • 验证接口返回内容
    直接在浏览器打开https://links.papareact.com/pyp和https://links.papareact.com/zp1,确认返回是否为JSON格式。如果是HTML页面(比如404页、验证弹窗),说明第三方接口临时故障或被拦截,这是最可能的原因。
  • 添加请求错误处理
    原代码未做任何异常处理,接口返回非JSON内容会直接导致启动失败。修改getStaticProps,加入状态检查和异常捕获:
    export async function getStaticProps() {
      let exploreData = [];
      let cardsData = [];
    
      // 处理explore接口请求
      try {
        const exploreRes = await fetch('https://links.papareact.com/pyp');
        if (!exploreRes.ok) throw new Error(`请求失败,状态码:${exploreRes.status}`);
        exploreData = await exploreRes.json();
      } catch (err) {
        console.error('获取explore数据失败:', err);
      }
    
      // 处理cards接口请求
      try {
        const cardsRes = await fetch('https://links.papareact.com/zp1');
        if (!cardsRes.ok) throw new Error(`请求失败,状态码:${cardsRes.status}`);
        cardsData = await cardsRes.json();
      } catch (err) {
        console.error('获取cards数据失败:', err);
      }
      
      return {
        props: { exploreData, cardsData }
      };
    }
    
  • 本地Mock数据兜底
    第三方接口不稳定时,建议在项目中添加静态Mock数据,保证项目能正常启动。新建data/mock.js:
    export const mockExplore = [
      { img: "https://links.papareact.com/5j2", distance: "12km away", location: "London" },
      { img: "https://links.papareact.com/1to", distance: "23km away", location: "Manchester" },
      { img: "https://links.papareact.com/40m", distance: "5km away", location: "Liverpool" }
    ];
    
    export const mockCards = [
      { img: "https://links.papareact.com/2io", title: "Entire homes" },
      { img: "https://links.papareact.com/q7j", title: "Unique stays" },
      { img: "https://links.papareact.com/s03", title: "Pet allowed" }
    ];
    
    然后在getStaticProps的异常捕获中导入使用:
    import { mockExplore, mockCards } from '../data/mock';
    
    // 在catch块中替换数据
    exploreData = mockExplore;
    cardsData = mockCards;
    
  • 检查本地网络环境
    确认本地网络是否能正常访问第三方接口,比如是否开启代理、VPN,或者运营商拦截了请求,可切换网络尝试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:40:16