nodejs express app serve static files from public/js folder not work

Viewed 88

I am developing a nodejs express project.

In the project there is a public folder with many subfolders like js, css, images etc. Originally serving files from these folders was using this code:

app.use(express.static(__dirname + '/public'));

All requested files can be served by the server using this, but files in the js folder not found by the server. If I change the folde name from 'js' to somthing else then it works.

So for example this not found by server if the requested url is /js/work/work.js:

app.use('/js',express.static(path.join(__dirname, '/public/js')));

but this is found if requested url is /asd/work/work.js:

app.use('/asd',express.static(path.join(__dirname, '/public/asd')));

Earlier I was using Mac and Windows for development but now I switched to Ubuntu and then happed this strange thing.

1 Answers

1. Add this middleware in the index.js above you set view engine

  app.use(express.static(path.join(__dirname, "public")));

2. Folder Structure

|__public/   
    |__ css/
        |__ css files...
    |__ js/
        |__ js files...

3. Import this way

Now you set the path to the public directory you have to give the path public folder when you import

//For CSS File
<link rel="stylesheet" href="/css/main.css" />

//For JS File
<script src="/js/script.js"></script>

You should now be all set up to access CSS or any file

Related