Search code examples
javascripthtmlnode.jsexpressstatic-files

How to serve simple static files along with html in NodeJS?


I'm trying to send an HTML file with its CSS and JS files in NodeJS using express.static() but it doesn't work.

I've done the same thing as in some videos but I don't know where the problem is. And also when I open the index.html without the server, it display the styles.

This is my app.js(server):

app.use(express.static('public'));
app.get("/", (req, res)=>{
    res.sendFile(`${__dirname}/index.html`);
});

HTML:

    <head>
        <link href="./public/styles.css" rel="stylesheet" type="text/css"/>
        <script src="./public/jQuery.js"></script>
        <script src="./public/main.js"></script>
    </head>

My public folder:

-node_modules
-public
    jQuery.js
    main.js
    styles.css
app.js
index.html
package.json
package-lock.json

Thanks in advance.


Solution

  • In app.use(express.static('public'));, the string 'public' refers to the directory where the module should search for static files, not the URL path which it should use for the search.

    src="/jQuery.js" will map to the public/jQuery.js file.

    To map URLs starting with /public/ to the public directory, you need to specify that as the first argument to use:

    app.use('/public', express.static('public'));
    

    And then src="/public/jQuery.js" will map to the public/jQuery.js file.