本地正常的Sanity博客拉取在Cloudflare生产环境报500错误求助
NextJS + Sanity部署到Cloudflare后出现500内部服务器错误
更新:问题已解决!使用NextJS 15.1.6搭配next-sanity 9.9.0版本,且不使用带有export const runtime = 'edge'的API调用即可解决。若未来部署在Cloudflare的Next.js应用API调用仍有问题,建议使用独立的Cloudflare Workers作为后端服务。
部署从Sanity Blog Studio拉取内容的NextJS应用时遇到问题:本地运行一切正常,但部署到Cloudflare生产环境后持续出现500 Internal Server Error。此前该拉取逻辑在Cloudflare生产环境中可正常运行,近期突然失效。
拉取内容的函数代码
import { client } from "@/client"; export async function getPostList(category: string ) { let CONTENT_QUERY; let params = {}; CONTENT_QUERY = `*[_type == "post" && $category in categories[]->title] | order(_createdAt desc) { ..., author->, "categoriesTitle": categories[]->title, "categoriesDescription": categories[]->description, "postImage": mainImage, body }`; params = { category }; const content = await client.fetch(CONTENT_QUERY, params); return content; } export async function getPostReadMore(slug: string) { const CONTENT_QUERY = ` *[_type == "post" && slug.current != $slug] | order(_createdAt desc) [0...4] { ..., author->, "categoriesTitle": categories[]->title, "categoriesDescription": categories[]->description, "postImage": mainImage, body } `; const params = { slug }; const content = await client.fetch(CONTENT_QUERY, params); return content; }
另一个拉取分类信息的函数:
import { client } from "@/client"; export async function getCategory(category: string) { const CONTENT_QUERY = `*[_type == "category" && title == $category][0] { "categoriesTitle": title, "categoriesDescription": description}`; const params = { category }; const content = await client.fetch(CONTENT_QUERY, params); return content; }
创建Sanity Client的代码
import {createClient} from 'next-sanity' import imageUrlBuilder from '@sanity/image-url' export const client = createClient({ projectId: "id", dataset: "production", apiVersion: "2024-03-11", // Set to `true` for production environments useCdn: true, }) export function urlFor (source: {}) { return imageUrlBuilder(client).image(source) }
Client调用代码
useEffect(() => { const fetchPosts = async () => { const content = await getPostList(category); const categoryData = await getCategory(category); const updatedContent = content.map((post: Posts) => ({ ...post, isMobile: isMobile ? true : post.isMobile, categoriesTitle: post.categoriesTitle[0], })); setPosts(updatedContent); setCategoryData(categoryData); }; fetchPosts(); }, [isMobile, category]);
依赖版本
"next": "^14.2.3", "next-sanity": "^9.8.60", "@sanity/image-url": "^1.1.0",
曾尝试使用Sanity官方NextJS模板单独部署,虽能获取文章标题,但无法正常展示文章内容。
内容的提问来源于stack exchange,提问作者Andrew Nguyen
相关产品推荐
相关产品推荐

