css files not found using express-handlebars

11,060

Solution 1

Change your static path.

const publicPath = path.join(__dirname, '../views');

Also, change href in html file

<link rel="stylesheet" href="/assets/bootstrap/css/bootstrap.min.css">

Solution 2

If following is your static folder, as you specified to express

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

and intended css file is bootstrap.min.css ; present at root inside of public folder then inside *.handlebar following will be path to your css file

<link rel="stylesheet" type="text/css" href="./bootstrap.min.css" />
Share:
11,060
Shobhit Srivastava
Author by

Shobhit Srivastava

Updated on June 04, 2022

Comments

  • Shobhit Srivastava
    Shobhit Srivastava about 2 years

    I'm using express-handlebars to render some html pages. The browser is not finding the css files that I'm linking to. This is what my server file looks like:

    const express = require('express');
    const exphbs = require('express-handlebars');
    const path = require('path');
    const _ = require('lodash');
    const bodyParser = require('body-parser');
    const socketIO = require('socket.io');
    const http = require('http');
    var static = require('node-static');
    
    var {mongoose} = require('./db/mongoose.js');
    
    var {User} = require('./models/user');
    
    const publicPath = path.join(__dirname, '../public');
    var app = express();
    app.engine('handlebars', exphbs({defaultLayout: 'main'}));
    app.set('view engine', 'handlebars');
    var server = http.createServer(app);
    var io = socketIO(server);
    const port = process.env.PORT || 3000;
    
    app.use('/', express.static(publicPath));
    app.use(bodyParser.json());
    
    app.get('/', (req, res) => {
        res.render('home');
    });
    

    And this is how I've formatted the urls on my main layout:

    <link rel="stylesheet" href="views/assets/bootstrap/css/bootstrap.min.css">
    

    The assets folder is in the root of the views folder. How can I fix this?

    Edit: This is my directory structure.

    enter image description here