【问题标题】:getStaticProps not really working on VercelgetStaticProps 并没有真正在 Vercel 上工作
【发布时间】:2021-11-29 18:11:01
【问题描述】:

编辑:我认为我的错误是这样调用我自己的 API,而不是在 getStaticProps() 中查询 MongoDB 数据库。我是这样重构的:

export async function getStaticProps() {
await dbConnect();

const user = await User.findOne({ email: process.env.EMAIL_USERNAME })
const projects = await Project.find({})

const { description, socials, title, skills } = user;
const sortedData = skills.sort((a, b) => (a.level < b.level ? 1 : -1));

if (!user || !projects) {
    return {
        notFound: true,
    };
}
return {
    props: {
        sortedData: JSON.parse(JSON.stringify(sortedData)),
        description,
        socials: JSON.parse(JSON.stringify(socials)),
        title: title ?? '',
        projects: JSON.parse(JSON.stringify(projects)),
    },
    revalidate: 60,
};

}

它似乎正在工作。我不确定这是否应该是这样,或者这样做不是一个好主意

我有这个项目,当我将它上传到 Vercel 时,我得到了Error: Request failed with status code 429. 我只有在 getStaticProps 中进行了三个 API 调用。我真的不知道发生了什么,因为我是新手。我看到有限制,但它是 3 个 API 调用?有什么我想念的吗?此外,即使没有错误,静态页面也不会刷新。实际上,即使我再次部署它,它也不会改变,我不明白。在我的电脑上使用外部 API 和外部 mongoDB 一切正常。

API 链接不是那个。只是在开发中使用这个

export async function getStaticProps() {
    const res = await axios.get('http://127.0.0.1:3000/api/get-skills');
    const res1 = await axios.get('http://127.0.0.1:3000/api/user-info');
    const res2 = await axios.get('http://127.0.0.1:3000/api/get-projects');
    const {
        data: { data },
    } = res;
    const {
        data: { description, socials, title },
    } = res1;
    const {
        data: { projects },
    } = res2;

    const sortedData = data.sort((a, b) => (a.level < b.level ? 1 : -1));

    if (!data || !res1 || !res2) {
        return {
            notFound: true,
        };
    }
    return {
        props: {
            sortedData: sortedData ?? [],
            description: description ?? '',
            socials: socials ?? [],
            title: title ?? '',
            projects: projects ?? [],
        },
        revalidate: 60,
    };
}

【问题讨论】:

  • 这是动态页面吗?是否从中生成了多个页面?
  • 只是索引页面有多个组件。我想我发现后坐力在构建时不起作用,所以这就是我没有获取数据的原因。仍然是 429 问题

标签: javascript next.js vercel


【解决方案1】:

看起来这是一个速率限制问题。而不是在getStaticProps中使用axios,而是在useEffect里面使用swr

 import useSWR from "swr"

创建一个获取函数:

const [firstState,setFirstState]=useState("")

const URL1='http://127.0.0.1:3000/api/get-skills'
const fetcher = async url => {
  const res = await fetch(url)
  const json = await res.json()
  setFirstState(json)
  return json ?? []
}


useEffect(()=>{
   fetcher(URL1)
 })

【讨论】:

  • 我可能误解了你的建议,但我认为我不允许在 getStaticProps 中使用钩子?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-13
  • 2016-12-25
  • 1970-01-01
相关资源
最近更新 更多