Hello! I recently started working through the Express tutorial and got snagged on the section where you setup the express.static
middleware
Obviously I’m just missing something very simple and silly but I just don’t see it.
Here’s the section I’m stuck on: https://www.freecodecamp.org/learn/back-end-development-and-apis/basic-node-and-express/serve-static-assets
And here’s a repl with my code: https://boilerplate-express.danjfletcher.repl.co
I’ve tried so many things at this point and can’t get it to work. So to simplify I actually added a call to app.listen(3000, => console.log('listening!'))
in my myApp.js
file just to rule out any of the bootstrapping that the boilerplate project sets up.
Current Situation
So here is my folder structure since I know a lot of people get this part wrong but I’m certain I have this correct:
- public
-- style.css
- views
-- index.html
myApp.js
<other files>
All files are unmodified with the exception of myApp.js.
Here is what that file looks like:
const express = require('express');
const path = require('path')
const app = express();
app.use(express.static(path.join(__dirname, 'public')))
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html')
})
app.listen(3000, () => console.log('Listening!!'))
With this I get a 404 for /public/style.css
What else have I tried?
I tried copying what was done in the Express docs:
app.use(express.static('public')
I tried what the description on the project alludes to which is:
app.use(express.static(__dirname + '/public')
I tried what the express docs recommends (which is actually what I have currently)
app.use(express.static(path.join(__dirname, 'public')))
I tried using various path arguments to the app.use()
function:
// like this
app.use('public', ...)
// and like this
app.use('/', ...)
// and this
app.use('./' ...)
I also thought maybe there was some weird permissions issue in my local environment so I tried to chmod
my project to 777
which also didn’t work.
I thought maybe there was something weird about my local setup because I work out of WSL2 so I tried deploying to Heroku and even just adding my code to the repl.it sandbox and both didn’t work.
Of course I’ve tried googling a ton and reading the documentation but all the related issues I find are not the problem I’m having. Usually when this isn’t working it’s because the path being used in express.static()
is wrong or the static files aren’t in the right directory, or the location of the entry point (server.js or myApp.js in my case) isn’t at the same level as the public
directory which mine is.
The only thing I’ve been able to figure out to be able to return that style.css
file is to manaully add a route that returns it like so:
app.get('/public/style.css', (req, res) => {
res.sendFile(__dirname + '/public/style.css')
})
Please help! I need an adult!
Which of course works, but not the solution I’m after!