我有一个非常严重的问题,我没有找到有关 Vercel (NextJS) 的答案。
我正在尝试在 Versel 上部署项目,并且我正在使用一些结构从 API 获取数据,例如:
export async function getStaticProps(context) {
const route = process.env.APIpath + 'api/category/getCategories'; //focusing here, ok on localhost
const res = await fetch(route)
const json = await res.json()
return {
props: {
data: json,
},
};
}
由于 fetch
仅使用绝对网址路径,我需要使用变量 process.env.APIpath
定义基本网址。
通过本地测试,我有 process.env.APIpath = 'http://localhost:3000/'
但是:我需要为 Vercel 部署定义一个生产变量,并且我正在使用无服务器功能。
关于 Vercel 的一些信息,根据这个 documentation,我们实际上可以fetch
获取数据。但是在部署过程中,我调用fetch
的页面总是报错,例如:
//this code triggers an error as code shown above, ok on localhost
const res = await fetch(process.env.APIpath + 'api/category/getCategory?_id='+ pid, {
method: 'post',
body: JSON.stringify(values, null, 2)
})
由于fetch
,我收到错误消息。当然,我知道在部署期间 Vercel 无法构建生产版本,因为我使用的是“硬编码”process.env.APIpath
。
如何明确定义 process.env.APIpath
(或任何不同的构建变量)来部署项目?请注意,每次 Versel 将通用项目链接生成为 nextjs-fhp5exsvo-testing.vercel.app
。
附言很高兴为您提供任何帮助,部署问题已经有大约 5 天了。
答案 0 :(得分:0)
我如何部分解决了我的问题
我没有使用 getStaticProps
和 getServerSideProps
从 API 获取数据,而是使用 useSWR
库。此解决方案似乎适用于 local
和 production
版本。
1.改为useSWR
而不是getStaticProps
无法使用 getStaticProps 运行代码
export async function getStaticProps(context) {
const route = process.env.APIpath + 'api/category/getCategories';
const res = await fetch(route)
const json = await res.json()
return {
props: {
data: json,
},
};
}
更改为 useSWR
,local
、test
和 production
的工作示例
import useSWR from 'swr'
import React from 'react';
//important to return only result, not Promise
const fetcher = (url) => fetch(url).then((res) => res.json());
const Categories = () => {
//getting data and error
const { data, error } = useSWR('/api/category/getCategories', fetcher)
if (error) return <div>Failed to load</div>
if (!data) return <div>Loading...</div>
if (data){
// {data} is completed, it's ok!
//your code here to make something with {data}
return (
<div>
//something here, example {data.name}
</div>
)
}
}
export default Categories
注意:我不确定 useSWR
能否与 SEO
完美配合,但根据此 link,我们甚至可以将它与 SSR
一起使用。
2.修改 MongoDB 设置。
当我使用 mongoDB
时,您需要正确地 check MongoDB settings
。一旦你这样做了,你需要check your API routes
(不是页面)在/pages/api/[apiname].js
中。只有在 API 路由工作(在 Vercel 上)之后,我才建议您开始编写本地版本。
3. 在 Vercel 上更改您的 deployment variables
。
您需要在 Vercel 上配置环境变量和其他一些变量。 More details here