首页 > 解决方案 > 从构建文件夹获取 React 文件时,.map 不是函数

问题描述

React我有一个用于前端的 node/express 应用程序。在开发模式下一切正常,在后端运行localhost:5000和前端运行之间有一个代理localhost:3000。但是,我的生产版本遇到了一个问题,我build通过在我的主服务器文件中包含以下内容从文件夹中获取静态 React 文件:

app.use(express.static(path.join(__dirname, "client", "build")));
app.get("*", function (req, res) {
  res.sendFile("index.html", {
    root: path.join(__dirname, "client", "build"),
  });
});

通过此设置,我可以在 上看到 React 应用程序localhost:5000,但在我收到的某些路线/页面上TypeError: a.map is not a function。这些错误似乎都是由在context提供程序中创建的数组触发的,该提供程序使用axios. 以下是其中一个 API 调用的示例:

  const getNodesApi = {
    url: "model/get-all-nodes",
    method: "GET",
    headers: {
      token: localStorage.token,
    },
  };
  async function getNodeData() {
    await axiosPm(getNodesApi)
      .then((response) => {
        const resData = response.data;
        setNodeData(resData);
        setLoading(false);
      })
      .catch((error) => {
        console.log(error.response);
      });
  }

我必须做些什么来设置 API 的基本 URL,还是有其他原因导致TypeError: a.map is not a function

编辑 1: .map 失败的示例

  const [options, setOptions] = useState(
    processes.map((process, index) => ({
      key: index,
      value: process.process_id,
      label: process.process_name,
    }))
  );

在此示例processes中来自context提供者。它最初定义为:

const [processes, setProcesses] = useState([]);

标签: node.jsreactjsexpress

解决方案


回答我自己的问题以提高知名度。这个问题是因为我在app.get为 React做完后安装我的后端/API 路由而引起的index.html。要解决此问题,请先挂载后端路由。

app.use(express.static(path.join(__dirname, "client", "build")));

//Routes - mounted from backend for API
mountRoutes(app);

//Routes - use from React app for frontend
app.get("*", function (req, res) {
  res.sendFile("index.html", {
    root: path.join(__dirname, "client", "build"),
  });
});

推荐阅读