david
david

Reputation: 43

css not rendered on all routes with express-handlebars

only base routes are rendered with css. so / , /home , /about and /portfolio have no problem. but /portfolio/project1 or about/biography are rendered without css

this is my code

const express = require('express');
const xhbs = require('express-handlebars');
const app = express();

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

app.use(express.urlencoded({
    extended:true
}));

const port = process.env.PORT || 3000;

app.engine('handlebars', xhbs({
    defaultLayout:'main'
}));

app.set('view engine', 'handlebars')

app.get('/portfolio', (req, res)=>{//css works fine on this route
        res.render('portfolio');
});    

app.get('/portfolio/project1', (req, res)=>{//css has no effect here
    res.render('project1');
});

and my files are structured this way

public
    css
        styles.css
views
    layouts
        main.handlebars
server
    server.js

Upvotes: 2

Views: 1179

Answers (3)

Farhad Aliyev
Farhad Aliyev

Reputation: 111

You can use base tag in the head section of handlebars file

<base href="http://localhost:5000">

Upvotes: 1

Ajit Kumar
Ajit Kumar

Reputation: 1505

You should use css link relative to root like '/css/styles.css' this may work.

Explanation: without '/' to the source address the request will go the current directory. eg. if make request to css/style.css and you are on path 'project/project1' then request to the style.css will be project/project1/css/style.css which will result in error 404.

With '/' in the beginning the request will be relative to the public root. Hence from any path the request will always go to the root of the public.

Hope it helps.

Upvotes: 1

C.Gochev
C.Gochev

Reputation: 1922

You should use an absolute path for the static middleware

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

Upvotes: 0

Related Questions