securethebags
securethebags

Reputation: 55

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

I have a directory called tree branch with a public folder with my index.html and a src folder that has my js(app.js/index.js) and css(index.css, app.css) files. Inside the tree branch directory is a file called server.js here is the code

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);

Here is the relevant code of index.html

  <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
   </body>

and 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>
  );
}

here is 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')); 

The request for index.html seems to be working however it only render's an empty page without the generated content in App.js. How do I connect this code so when I request the index.html it renders the jsx elements?

Upvotes: 1

Views: 56

Answers (1)

Muhammad Zeeshan
Muhammad Zeeshan

Reputation: 4748

While Development, you can run both server (React and Node) separately. For production, you will have to build your react app using

npm run build

and place that build in your node.js public folder. Now, you only need to run your node.js server in production and it will load the webpage with your JSX.

Upvotes: 1

Related Questions