GttMone
GttMone

Reputation: 33

Why does Express.js not render CSS if the path contains two '/'

So when I try to send a static page with 1 '/' in the path, for example:

app.get('/', (req, res) => {
    res.render('home.ejs')
})

It works perfectly fine and renders all the necesery css that is linked to the HTML page via the <link> attribute: <link rel="stylesheet" href="style.css">

The HTML and CSS files are in the same directory and the server.js file is in the previous directory: File directory

The server file is linked to the views directory via the:

app.use(express.static(__dirname + '/views'));
app.set('views', path.join(__dirname, 'views'));

But when I add another '/' in the path the css just won't render:

app.get('/projects/mcpaint', (req, res) => {
    res.render('mcpaint.ejs')
})

I've tried including the css in the html using the <style> tag and in that case the css is actually rendered.

Does anybody know how to fix that? Thanks, any help is appreciated!

Upvotes: 0

Views: 614

Answers (1)

AKX
AKX

Reputation: 169388

Since you're not showing your template, all I can do is refer to my crystal ball, which says you're doing something like

<link rel="stylesheet" href="public/style.css">

which is relative to whatever the URL of the view is; in other words, it'd request /projects/public/style.css if you're viewing /projects/projectx. Instead, you'd want

<link rel="stylesheet" href="/public/style.css">

to make it absolute to the server root.

Upvotes: 2

Related Questions