繁体   English   中英

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

[英]How to request react app over internet with express/node.js

我有一个名为tree branch的目录,其中包含一个包含我的 index.html 的public文件夹和一个包含我的 js(app.js/index.js) 和 css(index.css, app.css) 文件的src文件夹。 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)。 对于生产,您必须使用build您的react应用程序

npm run build

并将其放置在您的node.js公共文件夹中。 现在,您只需要在生产环境中运行您的node.js服务器,它就会使用您的JSX加载网页。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM