Error.invalid json响应json中位于位置0 sanity nextjs typscript的意外令牌T



嘿,伙计们,我有一个问题,我用react、typscript和sanity cms进行了构建,但问题是当我试图将构建部署到varcel时,它一直拒绝它,并说FetchError:无效的json响应体位于https://portfolio2-1-wn3v.vercel.app/api/getExperience原因:JSON中位置0处的意外标记T在我的本地机器上工作时,它会找到所有数据和一切。。。我读到getStaticProps或获取json时可能存在问题,是的,我确实将环境变量从http 3000中的base_url更改为varcel,但除此之外,我不知道我还应该做什么。。。。如果有人对这种错误有任何经验?这是的代码

`import {Experience} from '../typings'
export const fetchExperiences = async () =>{
const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getExperience`)
const data = await res.json()
const projects:Experience[] = data.experience

return experience
}`

getExercise.ts文件包含所有的api请求

import type{NextApiRequest,NextApiResponse} from 'next'
import {groq} from 'next-sanity';
import {sanityClient} from '../../sanity';
import {Experience} from '../../typings'
const query = groq`
*[_type == "experience"]{
...,
technologies[]->
}
`;
type Data ={
experience:Experience[]
}
export default async function handler(
req:NextApiRequest,
res:NextApiResponse<Data>,
){
const experience:Experience[]= await sanityClient.fetch(query)
res.status(200).json(JSON.parse(JSON.stringify({experience})))
}

这是index.ts文件的部分

export const getStaticProps: GetStaticProps<Props> = async() => {
const experience : Experience[] = await fetchExperiences();
const skills : Skill[] = await fetchSkills();
const projects : Project[] = await fetchProjects();
const socials : Social[] = await fetchSocials();
return{
props:{
experience,
skills,
projects,
socials,
},
revalidate:10
}
}

您看到的错误链接(https://portfolio2-1-wn3v.vercel.app/api/getExperience)是来自vercel的预览部署链接。这意味着,每次部署到vercel时,它都会创建此预览链接:https://yourappname-(一些独特的部署链接(.vercel.app.

但是,在您的api中,您可以传递${process.env.NEXT_PUBLIC_BASE_URL},它将在您的本地和可能的生产中工作,但不会在您的预览部署(暂存(中工作。

为了避免这种情况,不幸的是,您不能只提供/api/getExperience,因为只支持绝对URL。因此,我建议采用以下方法,避免使用[nextjs docs][1]中建议的API调用:

  1. 您在lib中创建了一个experience-queries.ts文件/
  2. 您在其中添加GROQ查询
export const getExperiences = groq`*[_type == "experience"]{..., technologies[]->}`
  1. 在index.ts中,在getStaticProps中,您调用getExperiences
const experiences = await sanityClient.fetch(getExperiences);

注意:要小心经验(一个项目(和经验(项目列表(之间的命名->如果你想得到它们,一定要说出你的名字。[1] :https://nextjs.org/docs/basic features/data fetching/get-static props#直接编写服务器端代码

最新更新