0
votes

Hi I am trying to serve react build assets from my static folder in express and it worked with CommonJS syntax. Now that I am using ES6 syntax with express, it is not serving the other files, but it does serve the index.html file:

GET /?session_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6ImI4Y2QxNTA0LTg3YmEtNGMzMC04ZmI3LWFhZDFkZWQ0ZmFkNCIsImlhdCI6MTYwNjczODExMiwiZXhwIjoxNjA2NzQxNzEyfQ.m4Lf5mimxD_8r14bT_Npg2Ql_ZkiJrFoy6mDfdkx2Sw 200 15.099 ms - 3011
GET /static/css/main.3dccf1f1.chunk.css 404 3.406 ms - 173
GET /static/js/2.0216aaa2.chunk.js 404 1.833 ms - 168
GET /static/js/main.71c89386.chunk.js 404 17.247 ms - 171
GET /manifest.json 404 0.543 ms - 152

Here is my code in app.js

import express from 'express';
import session from 'express-session';
import dotenv from 'dotenv';
import morgan from 'morgan';
import path from 'path';
import {socketListen,socketIO} from './socket/init.js';

dotenv.config({path: './config/config.env'});

import authController from './controllers/authController.js';


const app = express();

app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(session({
    resave: false,
    saveUninitialized: false,
    secret: process.env.SECRET_KEY,
    cookie: {secure: true}
}));
app.use(morgan('dev'));
//app.use(express.static(path.join(path.dirname(new URL(import.meta.url).pathname),'public')));
app.use(express.static((path.dirname(new URL(import.meta.url).pathname) + '/public')));
app.use('/api/v1/auth',authController);


const port = process.env.PORT || 5000;

app.get(['/','/nw','/nw/*'],(req,res) => {
    //res.sendFile(path.join(path.dirname(new URL(import.meta.url).pathname),'public','index.html'));
    res.sendFile('index.html',{root: 'public'});
});

socketListen(4000);

socketIO.on('connect',async() => {
    console.log('crypto client connected');
});

socketIO.on('event',async() => {

});

socketIO.on('disconnect',async() => {
    console.log('crypto client disconnected');
});


app.listen(port, () => console.log(`server is running on port ${port}`));

Here is my file structure:

nano_wall
 - app.js
 - /public
     - /static
     - /assets
     - index.html
     - asset-manifest.json
     - manifest.json
     - favicon.ico

I have used path.join with path.dirname(new URL(import.meta.url).pathname to replace __dirname for ES6, and while the import.meta.url code replaced __dirname, it did not seem to register properly with express.static(), so I used the {root: 'public'} config option instead.

1

1 Answers

0
votes

So I was playing around with express.static and looked at the serve-static index.d.ts file for a minute, I found that there is a dotfiles config option where you can decide how ./ is treated at the front of the file path, but I instead just used 'public' and it seemed to display properly.