next.js 下一个js 13缓存:'no-store'抛出错误

ej83mcc0  于 2023-10-18  发布在  其他
关注(0)|答案(1)|浏览(115)

看看这段代码

async function getData() {
  const res = await fetch('http://127.0.0.1:1337/api/posts', {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      Authorization:
        'Bearer 40742660cb44bedd348f8e69024c8f591f80124111fcfa2f1ec612f63e22be4d55ed429b4497887812da5e385f02a2b27e352551284c2c9793c33efd620c86f34058504b0ed9c76a13a6c7313d3b39826748ad0a15f5dab8ba85dbefba2ef29ab52290f98ca73a4359c6988063e96f0f5f68dafd25aac04f865e91dd9515915a',
    },
  })
  if (!res.ok) {
    throw new Error('Failed to fetch data')
  }
  return res.json()
}
export default async function page() {
  const result = await getData()
  console.log(result)
  return <div>page</div>
}

这段代码是从我的strapi后端获取我的一些职位。但问题是它每次都返回相同或缓存的结果,即使post在前端和后端发生变化。但当我添加cache:'no-store'cache:'no-cache'甚至revalidate:0选项时,它会转到错误并显示failed to fetch data

cclgggtu

cclgggtu1#

在我的项目中,我使用revalidate,它工作正常。你把这些选项传递到哪里?
我的代码示例

import qs from "qs";
import { getStrapiURL } from "./api-helpers";

export async function fetchAPI(
  path: string,
  urlParamsObject = {},
  options = {}
) {
  try {
    // Merge default and user options
    const mergedOptions = {
      next: { revalidate: 60 },
      headers: {
        "Content-Type": "application/json",
      },
      ...options,
    };

    // Build request URL
    const queryString = qs.stringify(urlParamsObject);
    const requestUrl = `${getStrapiURL(
      `/api${path}${queryString ? `?${queryString}` : ""}`
    )}`;

    // Trigger API call
    const response = await fetch(requestUrl, mergedOptions);
    const data = await response.json();
    return data;
    
  } catch (error) {
    console.error(error);
    throw new Error(`Please check if your server is running and you set all the required tokens.`);
  }
}

希望这对你有帮助。
您可以 checkout 整个项目here

相关问题