CSS and JS not loading – node.js and Express

March 11, 2020
7:34 AM
0

CSS3Express ModuleLayoutModuleNodeJsUI / UX

CSS and JS not loading – node.js and Express

Hello Node Js Developer!, how’s you’re project going?. Are you wondering how i recognized you as a developer, Oh com’n who is going to worry about css and js not loading in the node js while using express definitely its going to be us, yeah you’re right I’m a developer too (PHP) and i faced the same problem when starting node js for web development.

So lets come to the point, here is the issue i faced and i found the solution for this. If i’m right, in your project you may have used this bunch of code to call an index file to run a site page using express.

const path = require('path');
const express = require('express');
const app = express();

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

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});

app.listen(3333);

console.log('Now the server is running in url: http://127.0.0.1:3333');

And your html file would be something like this.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="public/css/node.css">
    <title>Node Js</title>
</head>

<body>
    <div class="container my-5 p-5 bg-warning">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Perspiciatis necessitatibus consequuntur repellat
        tempora voluptatibus et saepe architecto debitis laboriosam, fugiat enim corrupti laudantium rem quidem quo
        ratione odio deleniti distinctio!
    </div>
</body>

</html>

Right?, so when i started the node server and the page was rendered without the css. And when i see in the console, below message was shown and i really got stucked with this.

Refused to apply style from ‘http://127.0.0.1:3333/public/css/node.css’ because its MIME type (‘text/html’) is not a supported stylesheet MIME type, and strict MIME checking is enabled.

So here in this video you can see how i get rid of this error.


About Author

Karthikesavan

I'm the founder of Proficient Designers. I'm a full time PHP, Wordpress, Android app and UI/UX developer who is passionate in coding.

Comments & Replies