【问题标题】:Why my browser shows blank page when I run express server (React.js)?为什么我在运行 express server (React.js) 时浏览器显示空白页?
【发布时间】:2020-10-14 18:15:37
【问题描述】:

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

我的项目结构:

server.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>

【问题讨论】:

    标签: node.js reactjs express


    【解决方案1】:

    src 中没有 index.html。使用create-react-app 文件index.html 将在执行命令npm run build 时放入build。它会生成一个index.html,其中包含动态注入的 JS/CSS 的 URL。一种选择是您可以考虑将 React 应用程序放入 public,然后定位到由 build 生成的 index.html 文件夹npm run build

    // 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

    app.use(express.static('public'))
    

    static 也可以针对多个目录,以防您不想将 React 项目嵌套得太深:

    app.use(express.static('public'))
    app.use(express.static('build'))
    

    public 中有图片等静态资源是很常见的,但无论选择何种结构,都需要为静态资源指定路径,包括create-react-app 构建生成的 HTML、CSS 和 JS。

    【讨论】:

    • 感谢您的详细解答。我用res.sendFile(path.join(__dirname, '..','build', 'index.html')) 更新了我的get 函数内部,以针对npm run build 生成的index.html,就像你说的那样。我还添加了静态文件服务。但是,我对您回答的这一部分感到困惑:“一个选择是您可以考虑将 React 应用程序放入 public”我应该从我的 @ 中携带所有东西(我的反应组件、index.js 等...) 987654343@ 文件夹到public 文件夹之前运行npm run build?
    • 当然,让我澄清一下。 npm run build 生成的 build/index.html 应该包含在 express static 指定的路径中,以便可以有效地为其提供服务。您需要决定将哪些目录指定为静态资源路径,并确定目录build 的理想位置。
    猜你喜欢
    • 2017-04-08
    • 2021-04-26
    • 2011-05-04
    • 1970-01-01
    • 2013-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-30
    相关资源
    最近更新 更多