Next.js 13和/src/app中的静态组件,即使我设置了header:{授权:'x'} in fetch

nwsw7zdq  于 2023-04-11  发布在  其他
关注(0)|答案(1)|浏览(137)

我在/src/app文件夹中使用Next.js 13的实验模式,并且有以下组件
@/components/LinkList.jsx

const readLinks = async () => {
  return fetch(process.env.URL, { headers: { Authorization: '' })
    .then(response => response.json());
};

const Footer = async () => {
  const links = await readLinks();
  return (
    <ul>
      <li>Lista</li>
    </ul>
  );
};

export default Footer;

我在RootLayout. @/app/layout.jsx中使用了它

import Footer from '@/components/common/sections/Footer';
import Header from '@/components/common/sections/Header';
import { metaRootLayout } from '@/utils/meta';
import './globals.css';

export const metadata = metaRootLayout();

export default async function RootLayout({ children }) {
  return (
    <html lang="es">
      <body className="body">
        <Header />
        <main>
          {children}
        </main>
        <Footer />
      </body>
    </html>
  );
};

当执行命令'npm run build'时,它生成静态路由

Route (app)                                Size     First Load JS
┌ λ /                                      1.8 kB          113 kB
├ ○ /api/thanks                            0 B                0 B
├ ○ /notas                                 1.91 kB        87.4 kB
├ λ /notas/[slug]                          1.11 kB         113 kB
├ ○ /noticias                              1.91 kB        87.4 kB
├ ○ /videos                                1.91 kB        87.4 kB
└ λ /videos/[slug]                         1.11 kB         113 kB

但是,如果您向Authorization添加一个值(发送令牌需要它)。

const readLinks = async () => {
  return fetch(process.env.URL, { headers: { Authorization: TOKEN })
    .then(response => response.json());
};

它为我生成服务器的路由λ
有没有一种方法可以让静态路由持久化,但使用新的Next.js 13语法和app文件夹?
我尝试在发送授权令牌时,它会为我生成服务器路由,但是,当我从布局中删除它并开始在每个页面上使用它时,它不再影响所有内容。

sg2wtvxw

sg2wtvxw1#

我通过添加{ cache:'force-cache' }

const staticData = await fetch(`https://...`, { cache: 'force-cache' });

更多信息:

export default async function Page() {
  // This request should be cached until manually invalidated.
  // Similar to `getStaticProps`.
  // `force-cache` is the default and can be omitted.
  const staticData = await fetch(`https://...`, { cache: 'force-cache' });

  // This request should be refetched on every request.
  // Similar to `getServerSideProps`.
  const dynamicData = await fetch(`https://...`, { cache: 'no-store' });

  // This request should be cached with a lifetime of 10 seconds.
  // Similar to `getStaticProps` with the `revalidate` option.
  const revalidatedData = await fetch(`https://...`, {
    next: { revalidate: 10 },
  });

  return <div>...</div>;
}

https://beta.nextjs.org/docs/upgrade-guide#step-6-migrating-data-fetching-methods

相关问题