node.jsexpressviewbackendhsb

I am not able to access my css and js file in public to my index.hbs in views folder


I am trying to access css and js file which is in public folder from index.hbs which is inside views folder.

index.js file:

        const express = require('express')
        const path = require('path')
        // const hbs = require('hbs')
        const app = express()
        const port = 3000

        // const stat = path.join(__dirname, '../public')

        // app.use(express.static(stat))
        app.set('view engine' ,'hbs');
        app.set('/' ,path.join(__dirname, '/views'));


         app.get('/', (req, res) => {
          res.render('index', {})
          })
          app.get('/', (req, res) => {
          res.send("Hello")
          })

         app.listen(port, () => {
        console.log(`Example app listening at http://localhost:${port}`)
        })

LINK of css and JS in index.hsb:

<link rel="stylesheet" href="css/style.css">
<script src="javascript/main.js"></script>

Folder structure


Solution

  • 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

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

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