成功部署后无法通过前端连接到 heroku 上的后端

Not able to connect by frontend to backend on heroku after successful deployment

我已经在 heroku 上部署了我的 mern stack 应用程序。问题是我无法向我的后端发出任何请求。 我像这样将我的前端连接到我的后端...

API=http://localhost:5000/api

 import { API } from "../../backend";
import { signin } from "../../auth/helper";
export const getAllProducts = () => {
  return fetch(`**${API}/allProducts**`, { method: "GET" })
    .then((response) => {
      return response.json();
    })
    .catch((err) => {
      console.log(err);
    });
};

我想我正在本地主机上调用 api,这就是为什么我没有连接到后端。 我应该在这里做什么?

如果你还想要什么可以告诉我。

在客户端(前端)代码中,localhost 是最终用户的机器,因为代码在该机器的浏览器中运行。因此,当它试图在 localhost:5000/api 获取数据时,它会在最终用户的机器上寻找 Node.js 服务器,而不是 Heroku 上的实际生产服务器。

使用分配给您的应用程序的域 Heroku,而不是本地主机。您可以在 dyno 的设置中找到它,应该看起来像这样 https://yourapp.herokuapp.com/。此外,您可以使用 NODE_ENV env var 来设置 API 字符串,以便它在开发和生产中都有效:

const API = process.env.NODE_ENV === 'production' ? 'https://yourapp.herokuapp.com/api' : 'http://localhost:5000/api';