我是 React 新手。我想将我的 React 项目部署到 Heroku。为此,我实现了一个简单的快速服务器。但是,当我使用 node server/server.js
运行服务器时,我的浏览器在 localhost:3000
上什么也没有呈现。我在这里遗漏了一些明显的东西吗?
我的项目结构:
服务器.js:
const path = require('path');
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));
// create a GET route
app.get('/*', (req, res) => {
res.send(res.sendFile(path.join(__dirname, '../src/index.html')));
});
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
最佳答案
src
中没有 index.html
。使用create-react-app
文件index.html
,当命令npm run build
时,它将被放入build
中被执行。它生成一个 index.html
,其中包含动态注入(inject)的 JS/CSS 的 url。一种选择是您可以考虑将 React 应用程序放入 public
中,然后定位由 npm 生成的
:build
文件夹的 index.html
运行构建
// create a GET route
app.get('/*', (req, res) => {
// update this path to match how you set up express to serve static and where your build is output to
res.send(res.sendFile(path.join(__dirname, 'public', 'path', 'to', 'build', 'index.html')));
});
您还需要确保您有 static file serving设置为 express :
app.use(express.static('public'))
static
还可以定位多个目录,以防您不想将 React 项目嵌套得太深:
app.use(express.static('public'))
app.use(express.static('build'))
在 public
中拥有静态资源(例如图像)是相当常见的,但无论您选择哪种结构,都需要为静态资源指定路径,包括生成的 HTML、CSS 和 JS create-react-app
构建。
关于node.js - 为什么当我运行 Express 服务器(React.js)时,我的浏览器显示空白页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64359259/