node.js - 为什么当我运行 Express 服务器(React.js)时,我的浏览器显示空白页面?

标签 node.js reactjs express

我是 React 新手。我想将我的 React 项目部署到 Heroku。为此,我实现了一个简单的快速服务器。但是,当我使用 node server/server.js 运行服务器时,我的浏览器在 localhost:3000 上什么也没有呈现。我在这里遗漏了一些明显的东西吗?

我的项目结构:

My project structure

服务器.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/

相关文章:

javascript - 如何使用 ReactJS 获取总列​​数?

javascript - React - TypeError : _this. setState 不是函数

javascript - 无法在 React 中更改类

javascript - 如何在 NodeJS 的路由中使用 "?param=X"?

javascript - 如何在 Node js 中使用 ws (Websocket) 包创建/加入聊天室

node.js - 如何在 Plotly 中显示所有 x 轴刻度值?

node.js - 400 未找到项目的计费帐户。必须启用计费才能激活服务

node.js - 使 node.js 应用程序在 ubuntu 服务器上工作

javascript - req.session.passport 为空 : req. 用户未定义

javascript - Angular2 Webpack 和 Express