【发布时间】:2020-08-06 01:03:36
【问题描述】:
我有一个使用 create-react-app 制作的项目,我想在 express 中使用它(因为我需要一些后端功能)。
基本上,我的服务器在我运行它时会呈现一个空白页面...... 这是我的服务器的代码:
const express = require('express');
const path = require('path');
const app = express();
// Serve the static files from the React app
app.use(express.static(path.join(__dirname, 'public')));
// An api endpoint that returns a short list of items
app.get('/api/getList', (req,res) => {
var list = ["item1", "item2", "item3"];
res.json(list);
console.log('Sent list of items');
});
// Handles any requests that don't match the ones above
app.get('*', (req,res) =>{
res.sendFile(path.join(__dirname , 'public', 'index.html'));
});
const port = process.env.PORT || 5000;
app.listen(port);
console.log('App is listening on port ' + port);
如果我输入端点http://localhost:5000/api/getList,我可以看到结果,但是当我想为另一个端点显示我的反应应用程序时,页面是空白的。
react 应用使用不同的路由,我还在 package.json 中添加了一个代理。
我的服务器源文件与图像一样位于 react 应用程序的根目录。
有人知道为什么 react 应用程序不显示吗?
谢谢
【问题讨论】:
-
您是否构建了您的 React 应用程序? cra 的输出将创建一个
build文件夹 -
公用文件夹不会将您的反应应用程序作为静态资产包含。它是在开发过程中使用的,当你构建时,它的内容会被复制到构建文件夹中
-
不,我还没有构建。让我尝试构建它并将“公共”更改为“构建”
-
@azium 感谢构建后,它的工作原理。感谢您对公用文件夹的解释
标签: javascript node.js reactjs express create-react-app