如何防止 Next js 应用程序缓存我的 fetch 调用?

问题描述 投票:0回答:1

在我的 nextJS 应用程序中,我使用 fetch API 从 mongoDB 收集数据来获取参与者列表。

在本地开发环境中,并使用 Netlify 进行生产,效果很好。

但在本地制作中,当我在 Vercel 上托管时,它只会在第一次调用时显示。不管我刷新页面数据都没有改变我已经通过了

{cache: no-cache}
里面
fetch
但没有运气。我也尝试过
revalidate
。找不到原因。如果是因为生产原因,结果在 Netlify 中会类似 😐

我在这里给出相关的代码行。但如果需要更多上下文,我可以分享我的 GitHub 存储库链接



const [participants, setParticipants]  = useState([]);

  const fetchParticipants = async () => {

    try {

      const fetchedParticipants = await fetchAllParticipants();

      fetchedParticipants.sort((a, b) => a.serial - b.serial);

      setParticipants(fetchedParticipants);

    } catch (error) {

      console.log(error);

    }

  };

  // const [participant, setParticipant] = useState<IndexState['participant']>('')

  useEffect(() => {

    fetchParticipants();

  }, []);

动作/index.js



export const fetchAllParticipants = async () => {

  try {

    const response = await fetch("api/participants/all", {

      cache: 'no-cache', // don't cache

    });

    const data = await response.json();

    //console.logdata.allParticipants, " are all participants");

    return data.allParticipants;

  } catch (error) {

    console.log(error);

  }

};

app/api/participants/all/route.js



import connectToDb from '@utils/connectToDb'

import Participant from '@models/Participant'

export const GET = async () => {

    try {

        await connectToDb()

        const allParticipants = await Participant.find()

        // console.log(allParticipants, ' inside GET')

        return new Response(JSON.stringify({allParticipants,success: true, status: 200}))

        

    } catch (error) {

        console.log(error, ' error in route GET');

        return new Response(JSON.stringify({error}), {success: false, status:405})

    }

}

请协助查找原因。

我使用了 next js 13.8 和 14,但它们没有任何区别。

提前致谢

尝试在 fetch 中传递缓存相关选项,但没有结果。

在网上搜索我还没有发现这个问题讨论过。

javascript reactjs next.js vercel cache-control
1个回答
0
投票
export const dynamic = "force-dynamic";

^ 将其添加到您的路线顶部。ts

© www.soinside.com 2019 - 2024. All rights reserved.