Simple
Simple

Reputation: 437

How do you server css files with express?

I have seen a lot of the similar questions but nothing I do seems to work. The css file isn't being served. I keep getting the following error.

Refused to apply style from 'http://localhost:7000/public/css/styles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

launch-analytics.js:4 Uncaught TypeError: Cannot read property 'parentNode' of undefined at launch-analytics.js:4 at launch-analytics.js:5 (anonymous) @ launch-analytics.js:4 (anonymous) @ launch-analytics.js:5

my index.ejs file (path: user/Node/views/index.ejs)

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <link rel="stylesheet" href="public/css/styles.css" type="text/css">
    <body>
        <p>I am the home page</p>
    </body>
</html>

app.js file:(path: user/Node)

let express = require('express');
let bodyParser = require('body-parser');

let app = express();

let urlencodedParser = bodyParser.urlencoded({ extended: false })


app.set('view engine', 'ejs');

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

app.get('/', function(req,res){
    res.render('index');
});

app.listen(7000);

The styles.css file:

body{
    background-color: skyblue;
    font-family: verdana;
    color: white;
    padding: 30px;
}
h2{
    font-size: 49px;
    text-transform: uppercase;
    letter-spacing:2px;
    text-align: center;
}
p{
    font-size: 16px;
    text-align: center;
}
.text-field{
    display: flex;
    justify-content: center;
}

Upvotes: 0

Views: 1254

Answers (2)

thorup
thorup

Reputation: 11

Try changing

app.use(express.static("/public"));

to this

app.use(express.static(__dirname + "/public"));

Also answered here: Express-js can't GET my static files, why?

Upvotes: 1

Saptanto Sindu
Saptanto Sindu

Reputation: 46

It looks like app.use(express.static('/public')); is pointing to directory relative to root dir. Change it to app.use(express.static(__dirname + '/public'));

Upvotes: 3

Related Questions