javascript - 如何使用express/node.js通过互联网请求React应用程序

标签 javascript node.js reactjs

我有一个名为 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/

相关文章:

JavaScript 函数定时器。没有按预期工作

javascript - 单击时父元素的 AngularUI 弹出框样式发生变化

reactjs - 如果数据存在于 redux 存储中,则阻止 API 调用

javascript - D3 点与曲线面积图不匹配

javascript - Express + Node.js 无法加载图像

javascript - 无法理解 async/await Nodejs

node.js - 安装 NPM 包后将文件移至根目录

linux - 我如何知道 `yo` 从哪里运行?如何指定它运行的位置?

javascript - react Bootstrap 组件开关不工作

javascript - 状态给出不正确的结果