node.js - 从构建文件夹获取 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([]);
解决方案
回答我自己的问题以提高知名度。这个问题是因为我在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"),
});
});
推荐阅读
- reactjs - 下面的 react redux 代码片段有什么问题?
- javascript - 如何可靠地从 js Date 获取上个月?
- gitlab - Rsync:不能在 gitlab runner (CI/CD) 下工作,但可以通过 cli 工作。我错在哪里?
- python - 使用openpyxl在excel表中查找列号
- python - 如何从两个系列中创建熊猫系列,从公共列中选择第二个文件中的第一个匹配元素?
- php - PHP 安全图像上传控制?
- python-asyncio - zeromq 与 python 的简单异步示例
- r - 使用 write_xlsx 损坏/覆盖的 excel 文件
- vba - 向 VBA 函数添加计数器
- c++ - 如何解决由于引用绑定到 int 类型的空指针而导致的 stl_iterator 运行时错误?