I am currently trying to add my style.css file to home.ejs file render by express.js
But I keep receiving the following error
JavaScript
x
2
1
Refused to apply style from 'http://localhost:2000/cssFile/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
2
My file structure is like
JavaScript
1
7
1
cssFile
2
| style.css
3
views
4
| htmlFile
5
| | home.ejs
6
index.js
7
This is my express code
JavaScript
1
14
14
1
const express = require("express");
2
const app = express();
3
const path = require("path");
4
const mongoose = require("mongoose");
5
const Comments = require("./models/comments");
6
7
app.use(express.static(__dirname + "/public"));
8
app.set("views", path.join(__dirname, "views"));
9
app.set("view engine", "ejs");
10
11
app.get("/", (req, res) => {
12
res.render("htmlFile/home");
13
});
14
My home.ejs:
JavaScript
1
17
17
1
2
<head>
3
<meta charset="UTF-8" />
4
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
5
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
<title>Document</title>
7
<link
8
href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
9
rel="stylesheet"
10
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
11
crossorigin="anonymous"
12
/>
13
14
//buggy code
15
<link rel="stylesheet" type="text/css" href="/cssFile/style.css" />
16
</head>
17
I have been trying for another solution, but I just can’t solve mine.
Advertisement
Answer
My file structure is like
JavaScript171cssFile
2| style.css
3views
4| htmlFile
5| | home.ejs
6index.js
7
This is my express code
JavaScript131all your other code) (
2app.use(express.static(__dirname + "/public"));
3
In this JavaScript code, you’re telling express.static that you’re trying to service static files from a directory called “public”, which doesn’t exist. If you look in the “Network” panel in your browser, you’ll probably see that you’re getting served a 404 page, or sometimes a different HTML file.
Try changing your file structure to this:
JavaScript
1
8
1
public
2
| cssFile
3
| | style.css
4
views
5
| htmlFile
6
| | home.ejs
7
index.js
8