Luca C
Luca C

Reputation: 79

index.js not found in React application using Express (Node.js)

I am trying to use my own express server for the production of a React app, but I am getting a 404 status of not found for my index.js which have the React js script.

The folder structure that I am using is the following

server.js
+public
| index.html
|
__+ src
   |
   __ index.js

(index.html is in the public folder, index.js is in the src folder)

So In my server.js I have :

// Built-in Node.js modules
let fs = require('fs');
let path = require('path');

// Third-party Node.js modules
let express = require('express');


// Express App
let public_dir = path.join(__dirname, 'public');

// let port = 80; // production port
let port = 8000; // test/debug port

let app = express();
app.use(express.static(public_dir));

app.listen(port, () => {
    console.log("Now listening on port " + port);
});

and in my index.html I am calling in my head tag:

<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="./src/index.js"></script>

At the end, when I run the server.js I am getting the following error:

Failed to load resource: the server responded with a status of 404 (Not Found)

In case you might need this is my index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>

    <App />

  </React.StrictMode>,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();

Thank you!

Upvotes: 0

Views: 2406

Answers (1)

Ilijanovic
Ilijanovic

Reputation: 14904

An node.js server isnt like an apache server where you upload an index file and it automatically renders it , you need to tell node.js what to do at route /

// Built-in Node.js modules
let fs = require('fs');
let path = require('path');

// Third-party Node.js modules
let express = require('express');

// Express App
let public_dir = path.join(__dirname, 'public');

// let port = 80; // production port
let port = 8000; // test/debug port

let app = express();
app.use(express.static(public_dir));

//response with index file

app.get('/', function (req, res) {
   res.sendFile( __dirname + "/" + "index.html" );
})
app.listen(port, () => {
    console.log("Now listening on port " + port);
});

Upvotes: 0

Related Questions