首页 > 解决方案 > 通过 Express 服务时,Index.html 不呈现组件

问题描述

我在本教程的末尾https://www.freecodecamp.org/news/how-to-deploy-a-react-app-with-an-express-server-on-heroku-32244fe5a250/

我已将我的 App.js 更改为以下内容:

import React, { Component } from "react";
import "./App.css";

class App extends Component {
  render() {
    return (
      <div>
        <p>lmfao</p>
      </div>
    );
  }
}

export default App;

现在不幸的是,在运行“ npm run dev ”后访问 localhost:5000 时,虽然页面标题显示为“React App”并且页面源是 index.html,但 App 组件没有呈现,并且任何地方都没有错误。

这是访问 localhost:5000 的图片,它给出了 index.html 空白 index.html

现在有趣的是,如果我访问 localhost:3000 上的 React 服务器,组件会呈现。

我错过了什么?非常感谢

PS这里是Server.js

const express = require("express");
const app = express();
const path = require("path");
const port = process.env.PORT || 5000;

// Static file declaration
app.use(express.static(path.join(__dirname, "client/build")));

// production mode
if (process.env.NODE_ENV === "production") {
  app.use(express.static(path.join(__dirname, "client/build")));
  //  app.get('*', (req, res) => {    res.sendfile(path.join(__dirname = 'client/build/index.html'));  })
}

// build mode
app.get("*", (req, res) => {
  res.sendFile(path.join(__dirname, "/client/public/index.html"));
});

// start server
app.listen(port, (req, res) => {
  console.log(`server listening on port: ${port}`);
});

以下是 package.json 中的依赖项:

"devDependencies": {
    "eslint": "^6.5.1",
    "eslint-config-standard": "^14.1.0",
    "eslint-plugin-flowtype": "^4.3.0",
    "eslint-plugin-import": "^2.18.2",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-node": "^10.0.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-react": "^7.16.0",
    "eslint-plugin-react-hooks": "^2.1.2",
    "eslint-plugin-standard": "^4.0.1"
  },
  "dependencies": {
    "concurrently": "^5.0.0",
    "express": "^4.17.1",
    "react-router-dom": "^5.1.2"
  }

编辑:根据要求,这是该项目的 github 链接: https ://github.com/Dobermensch/ExpressTest.git 您必须为ExpressTest文件夹和客户端子文件夹执行npm install

标签: javascriptreactjsexpress

解决方案


您得到空白页的最可能原因是无法下载脚本包。

在浏览器中右键单击空白页面并选择“查看页面源代码”或类似菜单。您将看到 .html 文件的内容,包括<script>指向/some-path/some-name.js文件的标记。无法下载所有或部分文件。要确认是这种情况,只需通过将浏览器指向localhost:5000/some-path/some-name.js. 如果无法下载脚本包,请添加到 Express 的路由。


推荐阅读