我有一个名为 tree Branch
的目录,其中包含一个包含我的 index.html 的 public
文件夹和一个包含我的 js(app .js/index.js) 和 css(index.css, app.css) 文件。在 Tree Branch
目录中有一个名为 server.js
的文件,这里是代码
const express = require('express');
const path = require('path');
const app = express();
// Serve the js files and css from the React app
app.use('/js', express.static(path.join(__dirname, 'src/')));
app.use('/css', express.static(path.join(__dirname, 'src/')));
app.get('/', (req,res) =>{
res.sendFile(path.join(__dirname + '/public/index.html'));
});
const port = process.env.PORT || 3000;
app.listen(port);
console.log('App is listening on port ' + port);
这里是index.html
的相关代码
<title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
和App.js
function App() {
return (
<div className="App">
<header className="App-header">
<p>
Portfolio coming soon
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
这里是index.js
import React from 'react';
import ReactDOM from 'react-dom';
import '../css/index.css';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
对 index.html
的请求似乎有效,但它只呈现一个空页面,而没有在 App.js
中生成内容。如何连接此代码,以便当我请求 index.html
时它会呈现 jsx 元素?
最佳答案
在开发时,您可以单独运行两个服务器(React 和 Node)。对于生产环境,您必须使用
来构建
您的react
应用程序
npm run build
并将该构建放入您的 node.js
公共(public)文件夹中。现在,您只需在生产环境中运行 node.js
服务器,它就会使用您的 JSX
加载网页。
关于javascript - 如何使用express/node.js通过互联网请求React应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60182139/