Currently I'm learning expressjs, I don't understand why when using express.static()
there is some files that work properly and other than don't.
Here is my code:
const express = require("express");
const app = express();
app.use(express.static('./public'))
app.listen(5000, ()=>{
console.log("server listening on port 5000...")
});
All the files that i wanna access are in the same folder. But only style.css
has 301 status, there is ass well a file in the Chrome development network window called styles.css/
and has the status 404. How could I fix it?
Here is my html for what's worth
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<img src="descarga.jpg">
<div> AAAA</div>
</body>
</html>
The file structure is:
nodeTutorial
nodeTutorial/app.js
nodeTutorial/public/image.png
/public/styles.css
/public/index.html
Thanks for your help.
CodePudding user response:
I have mirrored Your project with small improvements.
From Your folder & file
structure and index.html
exactly from this line below :
<link rel="stylesheet" href="styles.css" />
...it appears that styles.css
should has status 301 OK (in my case 304 below in output screen). style.css
it looks like this file does not exist ??!
Try to hard refresh your Chrome browser Ctrl F5
and this issue should disappear. style.css
cannot appear there ! Good Luck ;-)
Serving static files in Express
app.js
const express = require("express");
const app = express();
const port = 5000;
app.use(express.static("./public"));
app.listen(port, () => {
console.log(`Server is listening at http://localhost:${port}`);
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div>
<h1>Static Files Express</h1>
</div>
<img src="run_013.jpg" />
</body>
</html>
styles.css
*,
*::before,
*::after {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
min-height: 100vh;
scroll-behavior: smooth;
text-rendering: optimizeSpeed;
line-height: 1.5;
}
img {
width: 50%;
height: 50%;
}
Output (chrome network) Version 98.0.4758.102 (Official Build) (64-bit)
Tested with: "express": "^4.17.3" node 16.13.0 Ubuntu 20.04