Applying Compiled CSS file in Node.js using Express and SASS not working as expected

Recently, I've delved into utilizing NodeJS with Express to serve my pug files. In addition, I decided to incorporate the "express-sass-middleware" to compile and serve the scss/css files in my project. While everything seems to be functioning as expected, I encountered an issue where the CSS styles are not being applied.

The content of my app.js file is as follows:

var express = require('express');
var sassMiddleware = require('express-sass-middleware');
var app = express();
app.set('view engine', 'pug');

app.get('/css/bootstrap.css', sassMiddleware({
  file: 'css/bootstrap.scss',
  precompile: true,
}));

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

app.listen(3000, function() {
    console.log('Example app listening on port 3000!');
});

Here is a snippet of my simple css file:

// $icon-font-path: /3rdparty/fonts;

// @import 'bootstrap/bootstrap';
// @import './node_modules/bootstrap-sass/assets/stylesheets/bootstrap/variables';

body
{
    background-color: green;
    font-size: 100px;
}

As for my index.pug file:

doctype html
html(lang='en')
  head
    title= varTitle
    link(ref='stylesheet' type='text/css' href='/css/bootstrap.css')
  body
    h1= varTitle

Upon starting the web server using "node app.js" and accessing http://localhost:3000, I can see "Hello World" displayed but unfortunately, the body background remains unchanged and the text size is not rendered as 100px. This suggests that the css file is not being properly applied. Strangely, when directly accessing http://localhost:3000/css/bootstrap.css, the correct css file is displayed.

I'm at a loss as to why the browser isn't applying the css styling despite being able to view the css source directly. I have even tried different browsers without success. None of them seem to apply the css file, leaving me puzzled. If anyone has any insights on what I might be overlooking here, your assistance would be greatly appreciated.

Answer №1

There is a typo in your index.pug file when loading the css file. You used ref instead of rel.

link(rel='stylesheet' type='text/css' href='/css/bootstrap.css')

I'm glad to assist you with this issue.

Answer №2

Your current nodejs server code may not be serving the static files properly. To rectify this issue, make sure to include your CSS directory so that it can be accessed from your HTML code:

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

Once you have added the above line of code, you will be able to load files from the public directory using the /static path prefix.

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I retrieve the elements that have been removed using $pull in mongoose?

Currently, I am utilizing $pull to eliminate a subdocument from an array within a document. It may be pertinent to note that the subdocuments in my case contain _id and are therefore indexed. Here is the JSON schema description: user: { _id: Strin ...

Make a quick call to the next function within the error handling module for a

Currently, I am facing an issue while trying to call the next function within the error handler of my node + express js application. In each controller, I have a middleware known as render which is invoked by calling next, and I wish to achieve the same f ...

Executing bower in appharbor deployment

I've scoured the internet but haven't been able to find a solution for my specific issue. My goal is to deploy a WebApp to AppHarbor with some extra tasks, but I'm running into a problem during the build process. <Target Name="NpmBuild" ...

Trouble with Click event not working in Electron and mouse cursor not changing when hovering over an HTML button?

I'm in the midst of a project that involves using the electron framework. Within my project, I have an HTML file, a CSS file, and a Javascript file. The issue at hand is that when I hover over a button, the expected hand pointer icon fails to appear d ...

Node.js TypeError: Unable to access property 'path' of an undefined object

In my Nodejs implementation, I am working on uploading various types of files (photos, mp3, pdf) to Amazon Web Services S3. Right now, I am focusing on uploading an mp3 file but keep encountering the error: "TypeError: Cannot read property 'path' ...

How can I create the effect of text changing color automatically after a specified time period has elapsed

I am currently dealing with a timer that is functioning properly, but I have a specific CSS inquiry. Essentially, what I would like to achieve is when the timer hits 30 seconds, I want the numbers to change to red color. $(function () { var $startTimer = ...

Developing with TypeScript - Utilizing the <reference path="....."> directive

Recently, I encountered an issue while adding a plugin to the TypeScript compiler. After including my code and compiling tsc.ts, it compiled without any errors. However, when I attempted to run it, I noticed that some variables declared in io.ts were missi ...

Adjusting HTML/CSS for various screen sizes and devices

I have designed a website, but when it is viewed on devices like iPad or iPhone, the layout does not adjust to fit the screen properly. The text box containing my name and social media buttons appears on the left side, while the background image is positio ...

Obtain the HTTP status code in Node.js

Currently, I am looking to retrieve the HTTP status code of a URL that is passed to a function. Up to this point, I have been using the request module for this purpose. The challenge I've encountered is that the request module fetches all the content ...

Having difficulty adjusting the margin-top for the menu div

Why am I unable to apply margin to my a links within the div identified by id="menu". I can successfully implement margin-left, but when attempting to use margin-top or margin-bottom, it does not work as expected. I wish to adjust the position o ...

Are Your Padding Styles Missing?

I've noticed that the text under the photos on this page in the main section (a.event) is not displaying the 5px padding top and bottom. Any suggestions for fixing this? Thank you! =) a.event { width:315px; height:auto; border:0; padding: 5px 0; } ...

Step-by-step guide on how to effectively send a NodeJS request and stream it into a separate response

Currently, I am in the process of developing an API to interact with a specific map service that requires the use of an API key. It is crucial for me to keep this API key private. To achieve this, I plan to make internal calls within my server's own A ...

Trouble with the HapiJS Proxy Solution

Summary I'm trying to figure out how to intercept a request, call a different route for an ID, save that ID in a session, and then proceed with the original request (especially PUT/POST requests with payloads) using the obtained ID. Context In my se ...

How can we target every nth child element universally?

I am working with an HTML structure that has a specific layout, and I need to target all odd <span> elements globally without considering their parent elements. Is there a way to style 1, 3, 5, 7, 9 in red color? I attempted to use :nth-child(odd) b ...

Encountering an unrecoverable SyntaxError while trying to deploy a website on Netlify

When using commands like npm start, npm run build, and pm2 start server.js, everything runs smoothly without any errors. However, I encounter an issue when trying to deploy my project on Netlify. The Chrome console displays the error: Uncaught SyntaxError: ...

Achieving Content Alignment Using CSS

I successfully implemented a design on my HTML page that divides it into three sections vertically, with each section having a different background color - white, gray, and black. The backgrounds stretch the full width of the page regardless of screen reso ...

Apply the child's style if the parent's sibling contains the specified class

I am struggling to add the class "bold" to a child element (span) of a parent element (button.usa-nav-link). This parent element has a sibling (ul li.active) with the class .active. When the sibling is active, I want the child element's text to be bol ...

Tips for adjusting the font color of user-provided text within an input box using HTML and CSS

HTML code:- <p><input type="text" placeholder="Enter your username"></p> CSS code:- .main-header input { width: 90%; padding: 1rem; margin: 20px 0px; border: none; border-bottom: 4px solid #5f5fb0; ...

Why is my Bootstrap row exceeding the page width when I resize it?

As a newcomer to Bootstrap, I have been following tutorials to learn more about it. Currently, I am attempting to recreate the layout of Google's homepage. However, I am facing challenges with the grid system's responsiveness. I have managed to ...

Attempting to develop a react application, however encountering an error in the process

$ npx create-react-app my-app npm ERR! code ENOENT npm ERR! syscall spawn C:\MongoDb\mongosh-1.0.1-win32-x64\mongosh-1.0.1-win32-x64\bin npm ERR! path C:\Arya\web development\react-project-first npm ERR! errno -4058 ...