【发布时间】:2022-01-07 05:09:54
【问题描述】:
我正在尝试将我的 nextjs Web 应用程序部署到 vercel。
当我部署我的网站时,我得到了这个:
> Build error occurred
FetchError: request to http://localhost:3000/api/products failed, reason: connect ECONNREFUSED 127.0.0.1:3000
我在这里获取localhost:3000 的数据,它在npm run dev 时有效。
但是现在我想构建和部署我的项目,我不能再从localhost 获取,而且我还不知道我的域名。那么,vercel 在构建我的网站时如何从我的 API 路由中获取数据呢?
export const getStaticPaths = async () => {
const res = await fetch("http://localhost:3000/api/products");
const products = await res.json();
const paths = products.map((product) => ({
params: { productId: product.id },
}));
return {
paths: paths,
fallback: false,
};
};
export const getStaticProps = async (context) => {
const res = await fetch(
`http://localhost:3000/api/products/${context.params.productId}`
);
const product = await res.json();
return {
props: {
product,
},
};
};
【问题讨论】:
-
这是否回答了您的问题:Fetch error when building Next.js static website in production?您不应从
getStaticProps中的内部 API 路由中获取。相反,直接导入 API 路由中使用的逻辑。
标签: javascript reactjs api next.js vercel