【问题标题】:How to fetch data from Nextjs API route when build and deploy? [duplicate]构建和部署时如何从 Nextjs API 路由中获取数据? [复制]
【发布时间】: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,
    },
  };
};

【问题讨论】:

标签: javascript reactjs api next.js vercel


【解决方案1】:

如果前端和后端在同一服务器/域上运行/托管。您不必指定主机名,它将指向与客户端相同的域。

export const getStaticPaths = async () => {
  const res = await fetch("/api/products");
  // something
};

您可以为主机使用环境变量。在项目根目录上创建一个 .env 文件。 https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser

.env

NEXT_PUBLIC_ENV = development;

组件

export const getStaticPaths = async () => {
  const url =
    "development" === process.env.NEXT_PUBLIC_ENV
      ? "http://localhost:3000/api/products"
      : "https://example.com/api/products";
  const res = await fetch(url);
  // something
};

【讨论】:

  • 这不起作用。我收到此错误TypeError: Only absolute URLs are supported
  • 哪一个不工作?
  • 我什至无法使用fetch("/api/products") 获取npm run dev 中的数据。我必须在 URL 之前添加localhost:3000。但如果我从localhost 获取,我将无法部署我的网站。
  • 我都试过了,我认为它不允许我使用 /api/products 并且只允许绝对 URL。
  • 我试过了。它不起作用,因为仅支持绝对 URL。但是部署之前不知道自己的域名...
猜你喜欢
  • 2022-10-24
  • 1970-01-01
  • 1970-01-01
  • 2021-02-18
  • 1970-01-01
  • 2021-10-19
  • 2018-10-01
  • 1970-01-01
  • 2021-08-08
相关资源
最近更新 更多