Sanity + Next.js 报错:TypeError: Cannot read properties of undefined (reading 'fetch')
Next.js 连接 Sanity 后端时出现 TypeError: Cannot read properties of undefined (reading 'fetch')
我正在使用 Sanity 作为后端搭建个人作品集网站,Sanity Studio 已完成正常配置,数据库也可正常访问,但 Next.js 无法与后端建立正确连接。
连接文件代码
import { createClient } from "next-sanity"; import createImageUrlBuilder from "@sanity/image-url"; export const client = createClient({ projectId: "p079sml5", dataset: "production", apiVersion: "2023-01-31", useCdn: false, });
为方便调试,暂时未将配置信息存入环境变量。
接口文件代码
import { NextApiRequest, NextApiResponse } from "next"; import { groq } from "next-sanity"; import { client } from "sanity"; import { Social } from "./typings"; const query = groq` *[_type == "social"] `; type Data = { socials: Social[]; }; export default async function handler( req: NextApiRequest, res: NextApiResponse<Data> ) { const socials: Social[] = await client.fetch(query); res.status(200).json({ socials }); }
报错信息
调用 http://localhost:3000/api/getSocials 时出现错误:
error - TypeError: Cannot read properties of undefined (reading 'fetch')
报错位置为:handler (webpack-internal:///(api)/./src/pages/api/getSocials.ts:15:70)
编辑器中 fetch 方法可被自动补全,看似导入正常,但错误明确指向 client 未定义。尝试切换开发环境及对应项目ID,均无法解决问题。
解决方法
更新:问题已解决,仅将 Sanity 客户端连接文件移动至其他文件夹即可正常运行。
内容的提问来源于stack exchange,提问作者FimbulWinters
相关产品推荐
相关产品推荐

