在 Next 14.1.1 中,我在 fetch 函数中使用两种不同的服务器方法,并收到错误:
Invariant: headers() expects to have requestAsyncStorage, none available.
getLocale()
导入next-intl/server
和从draftMode()
导入
next/headers
generateStaticParams()
dev
在获取函数下方:
import qs from "qs";
import { getAuthToken } from "../utils/strapiHelper";
import { draftMode } from "next/headers";
import { getLocale } from "next-intl/server";
import { defaultLocale } from "../i18n";
export async function fetchStrapi(url: URL, params?: {}) {
const authToken = getAuthToken();
const headers = {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${authToken}`,
},
};
const locale = (await getLocale()) || defaultLocale; // will not work when fetching client-side
const { isEnabled } = draftMode();
const existingSearchParams = qs.parse(url.search, {
ignoreQueryPrefix: true,
});
const searchParams = {
...existingSearchParams,
locale,
...(isEnabled && { publicationState: "preview" }),
...params
};
url.search = qs.stringify(searchParams, { addQueryPrefix: true });
try {
const response = await fetch(url, authToken ? { ...headers } : {});
const data = await response.json();
return data;
} catch (error) {
console.error("Error fetching data:", error);
throw error;
}
}
这里是执行获取操作的组件:
import React from "react";
import Link from "next/link";
import { notFound } from "next/navigation";
import { getArticles, getArticlesBySlug } from "@repo/web/services/articles";
const Article = async ({ params }: { params: { slug: string } }) => {
const { slug } = params;
const article = await getArticlesBySlug(slug);
if (!article || !article?.data?.length) {
notFound();
}
return (
<>
<div>{JSON.stringify(article)} </div>
<Link href={"/"}>Retourner à l'accueil</Link>
</>
);
};
export default Article;
export async function generateStaticParams() {
const slugs = await getArticles({ locale: "all" });
return slugs.data.map((data) => ({
slug: data.attributes.article_slug,
locale: data.attributes.locale,
}));
}
export const dynamicParams = false;
generateStaticParams