Express.js cant apply stylesheet

Issue

When running my HTML+ExpressJS code i have ran into an issue to do with CSS. When i go to dev tools in the browser i see Refused to apply style from 'https://localhost:5000/public/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

Code:

ExpressJS

const app = express();
app.use(express.static('public'));
app.get('/', (req,res) => {
    res.sendFile('/home/pi/website/index.html');
});

app.listen(5000, () => console.log('http://localhost:5000'));

HTML:

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <title>homepage</title>
  <link rel="stylesheet" type="text/css" href="public/style.css" media="screen" />
  </head>
  <body>
    <h1 class=title>Hello!</h1>
    <h1 class=title>This page is running NodeJS on a Raspberry Pi 4 4GB</h1>
  </body>
</html>

Solution

Your link:

href="public/style.css"

will not work with

app.use(express.static('public'));

because that will be looking inside the public directory for public/style.css in your server file system which means it’s actually looking for public/public/style.css and I assume you don’t have the file system set up that way. You don’t show exactly where style.css is in your server file system, but if it’s directly in the public directory you are pointing express.static() at, then you should be using:

href="/style.css"

Answered By – jfriend00

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published