css files not found using express-handlebars

Shobhit Srivastava picture Shobhit Srivastava · Jan 11, 2017 · Viewed 9.6k times · Source

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

Answer

Mukesh Sharma picture Mukesh Sharma · Jan 12, 2017

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">