javascript - 通过 Express 服务时,Index.html 不呈现组件
问题描述
我已将我的 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
现在有趣的是,如果我访问 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
解决方案
您得到空白页的最可能原因是无法下载脚本包。
在浏览器中右键单击空白页面并选择“查看页面源代码”或类似菜单。您将看到 .html 文件的内容,包括<script>
指向/some-path/some-name.js
文件的标记。无法下载所有或部分文件。要确认是这种情况,只需通过将浏览器指向localhost:5000/some-path/some-name.js
. 如果无法下载脚本包,请添加到 Express 的路由。
推荐阅读
- jspdf - 使用 jspdf-autoTable margin top 两个表之间出现差距
- ios - UITableVIew 无法正确渲染 UITableViewCell
- python - 一列中的值基于另一列中的条件
- php - Magento 2 - 扩展 onepage.phtml 以添加自定义 JS
- jquery - jQuery异步回调延迟返回[object] [object],但控制台显示值
- android - 在android中获取SHA1指纹
- c# - 如何在服务器机器的 Web API 中验证 WPF 应用程序 Azure 令牌
- c - 关于数组外指针算术的 C 标准
- javascript - 无法在 iOS Safari 中播放声音
- python - 获取 JSON 和 Python 中的特定值