skip to Main Content

My built react codes are stored in "/build" folder.

Here is my node code (i.e. /server/index.js):

import dotenv from 'dotenv';
import Express from 'express';
import http from 'http';
import path from "path";
import { fileURLToPath } from 'url';
let app = new Express();
let httpServer = http.createServer(app);

app.use(Express.json());
dotenv.config({ path: './.env.' + process.env.NODE_ENV });
if (process.env.NODE_ENV === "production") {
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = path.dirname(__filename);
    
    app.use('/Manual',Express.static(path.resolve(__dirname, '../public/Manual')));
    app.use(Express.static(path.resolve(__dirname, '../build')));
    app.get('*', (req, res) => {
        res.sendFile(path.resolve(__dirname, '../build', 'index.html'));
    });
}
httpServer.listen(process.env.REACT_APP_SOCKET_PORT, () => {
    console.log('Express server is running on localhost:' + process.env.REACT_APP_SOCKET_PORT);
});

The problem is that the browser can fetch /static/css/main.xxxxxxxx.css successfully.

But the browser cannot fetch /static/js/main.yyyyyyyy.js content, it just returns the index.html content.

How can I fix the problem?

2

Answers


  1. Chosen as BEST ANSWER

    Finally, I found that I have not uploaded the latest build/index.html to the server. After I uploaded the latest index.html, it works.


  2. It is my understanding path.resolve([…paths]) only works with absolute paths. However, you are using relative paths trying to access "../build" and "../public". I would update those path to absolute ones:

    app.use('/Manual',Express.static(path.resolve(__dirname, 'public/Manual')));
        app.use(Express.static(path.resolve(__dirname, 'build')));
        app.get('*', (req, res) => {
            res.sendFile(path.resolve(__dirname, 'build', 'index.html'));
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search