I am working on my first node/express project, and I am having difficulty with the express.static function within .use. I have explored all the documentation and with my beginner mind it is a bit too abstract apparently for me to apply to this, but with all of the different solutions I have tried it always returns 404 not found.
file structure:
Project
|
+-- index.js
+-- package.json
|
+-- public
| |
| \-- documentation.html
const express = require('express');
const app = express();
const path = require('path')
//this is not working
app.use(express.static(__dirname + '/public'));
I have also tried
app.use('/documentation.html', express.static('public))
as well as trying to use path.join
to specify the file path.
I have verified I have the correct version of express and node.
Not sure how to proceed
// this all works
let topMovies = [array that is working]
app.get('/', (req, res) => {
res.send('Welcome to my movie list!')
});
app.get('/movies', (req, res) => {
res.json(topMovies)
});
app.listen(8080, () => {
console.log('Your app is listening on port 8080.')
})
I expected writing localhost:8080/documentation.html
to return my html file, and it said 404 not found
.
Use a route handler for /documentation
(or /documentation.html
):
app.get("/documentation", (req, res) => {
res.sendFile(path.join(__dirname, "public/documentation.html"));
});
This will take all GET request and return the file from the filesystem.
The middleware app.use
and Express static methods can also be removed.
express.static is best used when you are serving a larger number of files that all have the same URL prefix (i.e. /js/*.js
or /docs/*.html
).