Jelani Thompson Jelani Thompson - 1 month ago 14
Javascript Question

Express: Styles/Scripts called by Template Engine (Pug) not Loading

I'm currently trying to load my scripts and styles called in Pug. However, even when I use express to serve static files, the only thing that loads is the webpage with no styles, images or scripts. This is my directory structure:

enter image description here

My server.js file executed by Gulp contains this:

const path = require('path')
const express = require('express')
const app = express()

app.set('view engine', 'pug')
app.set('views', 'src/pages')
app.use(express.static(path.join(__dirname, '../../docs')))
console.log(path.join(__dirname, '../../docs'))

app.get('/', function(req, res) {
console.log('Welcome!')
res.render('index');
})

// Get post data from login and use encodeURIComponent on password with POST URL
app.get('/login', function(req, res) {
console.log('Request received')
res.end()
})

let server = app.listen(8080)
console.log('Listening on port 8080')


Here's the error that gets returned:
enter image description here

I'm not exactly sure what it is I'm doing wrong. Could someone help me figure out what's going wrong here? Thanks!

Answer

References to static assets should not include the folder you set as static in express. For example: /docs/styles/main.css -> /styles/main.css

Also try doing app.use(express.static('docs')) That should be enough.