Skip to content
Advertisement

Refused to apply style from ‘http://localhost:2000/cssFile/style.css’ because its MIME type (‘text/html’)

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

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.

My file structure is like

cssFile
 | style.css
views
 | htmlFile
 |   | home.ejs
index.js

This is my express code

const express = require("express");
const app = express();
const path = require("path");
const mongoose = require("mongoose");
const Comments = require("./models/comments");

app.use(express.static(__dirname + "/public"));
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");

app.get("/", (req, res) => {
  res.render("htmlFile/home");
});

My home.ejs:

...
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
      crossorigin="anonymous"
    />

    //buggy code
    <link rel="stylesheet" type="text/css" href="/cssFile/style.css" />
  </head>

I have been trying for another solution, but I just can’t solve mine.

Advertisement

Answer

My file structure is like

cssFile
 | style.css
views
 | htmlFile
 |   | home.ejs
index.js

This is my express code

... (all your other code)
app.use(express.static(__dirname + "/public"));

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:

public
 | cssFile
 |  | style.css
views
 | htmlFile
 |   | home.ejs
index.js
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement