I'm learning Node.js with Express to get a little server running for studying. I'm getting response code 404 for all requests to files linked in my index.html
file (e.g. the .css
, .js
, and image files).
The code I used to send index.html
:
routes.get('/', (req, res) => {
res.sendFile(path.join(__dirname, "/clientSide/index.html"));
})
If I change the path to the whole folder instead:
routes.get('/', (req, res) => {
res.sendFile(path.join(__dirname, "/clientSide"));
})
I get in my browser the path from my hard drive to the folder, but I still can't view the files that way.
The clientSide
folder contains index.html
, app.js
, style.css
, and 2 or 3 images, all in the same folder. I can't view any of them.
I changed the filenames and folder name, and checked for capitalization to no avail.
SOLVED
I was using app.use(express.static(path.join(__dirname, "static/")));
With app = express();
That does not work, but using routes.use
instead of app.use
, while routes = express.Router();
, is what solves that
The end
In your first code snippet, when you write:
routes.get('/', (req, res) => {
res.sendFile(path.join(__dirname, "/clientSide/index.html"));
})
You defined a new middleware function for requests to route /
; that's what routes.get('/', ...)
does. Assuming your server is running on port 3000, route /
maps to http://127.0.0.1:3000/
. For exactly that URL, and no other, Express executes your provided function, which replies with the the file clientSide/index.html
. Thus, when your browser requests http://127.0.0.1:3000/
, Express responds correctly.
But you've said nothing about the other files, such as http://127.0.0.1:3000/style.css
, which would be route /style.css
. You haven't defined any middleware for that route. So Express, not knowing what to do, by default responds with 404 and an error message. Thus, when your browser tries to load http://127.0.0.1:3000/style.css
while fetching the resources referenced in index.html
, the stylesheet fails to load.
Your second code snippet doesn't fix anything. It really makes things worse, because res.sendFile()
can't send folders (how would that even work?) and that generates errors. You still haven't defined routes other than /
, and now all your files are inaccessible.
To actually solve the problem, you could, theoretically, tediously define a route for every file, or more cleverly define one route with a route parameter. But serving a static folder with Express is a solved problem. You can simply offload the work to express.static
by replacing all your code with:
routes.use(express.static(path.join(__dirname, "clientSide/")));
To go even further, you don't need Express or Node.js for a static file server. Try nginx. And for simple webpages, you don't need a server at all; just double-click index.html
and let your browser open it.