score:28

Accepted answer

after trying many different things through trial/error, the solution is quite simple:

serve the /client/build folder in the static call, like so:

app.use(express.static(path.join(__dirname, '../client/build')));

score:0

//on your react app run

npm run build

//the insert the following code on your server

const path = require("path");
app.use(express.static(path.join(__dirname,"nameofyourreactapp","build")))

//replace nameofyourreactapp with the name of your app

score:0

my project structure
project
-->client
back end(express)\

after using npn run build i found out that index.html in build was using wrong directory of css files or static instead of using

const path = require('path');
app.use(express.static(path.join(__dirname, '/client/build/')));

i know i also tried ../client...... but not working

so what i did is cut and paste static folder of build in root directory this image can give you the idea, and its working structure

score:2

i had the same problem for a while and i would say that the solution that works is divided into 2 parts to avoid problems with the routers

  1. server the static from the cra build (in your case the client/build)
const buildpath = path.normalize(path.join(__dirname, '../client/build'));
app.use(express.static(buildpath));
  1. set a final route (after all other routers in your server) to use the following:
const rootrouter = express.router();
/* 
* all your other routes go here
*/
rootrouter.get('(/*)?', async (req, res, next) => {
  res.sendfile(path.join(buildpath, 'index.html'));
});
app.use(rootrouter);

Related Query

More Query from same tag