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

JavaScript button mouse enter

There seems to be an issue with this code. The button is not functioning properly after hovering over it, even though it was copied from the instructional website where it works fine. <html> <head> <title>Button Magic</t ...

Encountering an error while trying to run a Next.js application on Linux Mint

View the error screenshot After creating a new Next.js app with npx create-next-app, I ran npm run dev and encountered the following error message ...

Issues with environment variables are causing errors when using npm version 9.6.4 and node version 19.9.0

It is commonly believed that every entry in your package.json can be accessed as an environment variable. For instance, using npm_package_dependencies_svelte will provide you with the version of svelte currently installed, or npm_package_author_email will ...

Flexbox: Arrange header and footer in a sidebar layout using flexbox styling

In my content layout, I have structured the sections as header, content, and footer. While I want to maintain this order for small devices, I am looking to shift the header and footer to the sidebar on desktop. I have already implemented this using floats ...

An error occurred while attempting to generate two requests on the API

My online store consumes an API, but I am having trouble with the requests that the site is making. Every time I make a request, I receive two: one with OPTIONS and another with POST. This causes the API to become jumbled up. Can anyone offer some assist ...

Error encountered when attempting to install a module using npm: "tunneling socket

Having trouble installing nodejs modules using npm on Windows while behind a proxy? Here is how I set up the proxy: npm config set proxy internet.cp:8080 npm config set proxy-http internet.cp:8080 Unfortunately, when attempting to install a packet, I enc ...

How to prevent npm from being accessed through the command prompt

I recently began working on a ReactJs project. However, I am facing an issue where after starting npm in Command Prompt, I am unable to enter any text. Should I close the cmd window or is there a way to stop npm? You can now access your project at the fol ...

Nvm does not have the ability to generate an Angular project

Creating an Angular project using nvm has been a bit of a challenge for me. Here are the steps I took: D:\Project1>nvm list The output showed: 14.16.1 Next, I ran the following command. F:\Ashok\Angular\Angular>nvm use 14.16.1 ...

unable to deploy nestjs application on cpanel hosting

I encountered an issue while trying to deploy my Nestjs project to hosting. The error message I received was: returncode: 1 stdout: [email protected] start:prod /home/enebbvmz/server/dist node main.js stderr: /home/enebbvmz/nodevenv/server/dist/ ...

Issue with Google Maps API fetching data is resolved

const express = require('express'); const app = express(); const { Client } = require('@googlemaps/google-maps-services-js'); const googleMapsClient = new Client({apiKey:"myGoogleApiKey"}); app.use(express.json()); app.ge ...

Are the JQuery appended elements exceeding the width of the parent div?

I have an HTML div that is styled using the Bootstrap class span9. <div class="span9"> <div id = "selectedtags" class="well"> </div> <button class="btn" type="button" id="delegatecontent">Generate report</button&g ...

What is the best way to monitor the status of the mongoose connection in Node

Is there a way to continuously monitor the status of the mongoose package connection string after starting an instance, similar to when running 'npm start'? I attempted the following approach: setInterval(function(){ if(mongoose.connection.re ...

The value returned by EntityRecognizer.resolveTime is considered as 'undefined'

In my bot's waterfall dialog, I am utilizing the LuisRecognizer.recognize() method to detect datetimeV2 entities and EntityRecognizer.resolveTime() to process the response. Here is an example of how I have implemented it: builder.LuisRecognizer.recog ...

Interactive font-awesome icons within an interactive dropdown menu

I am currently facing an issue with using two Fontawesome icons in a clickable dropdown menu. The dropdown menu does not toggle when I click on the icons directly; however, it works when I click on the padding around them. The example provided by W3schools ...

What steps can I take to ensure my CSS selector for the element is functioning properly?

Here is an example of some code: <html> <head> <style> .test{ background-color: red; p { background-color: yellow; } } </style> </head> <body> <div class="test"> ...

Trouble with setting up custom static route

Greetings! I am currently working on setting up my project in React and here is my current project structure: -public --w ---dist ----bundle.js ---index.html -server --server.js -src --app.js -webpack.config.js -package.json -.babelrc For my server, I am ...

Having trouble transferring files to an unfamiliar directory using Node.js?

const { resolve } = require("path"); const prompt = require('prompt'); const fsPath = require('fs-path'); // Retrieve files from Directory const getFiles = dir => { const stack = [resolve(dir)]; const files = []; whi ...

How to add icons to HTML select options using Angular

Looking for a way to enhance my component that displays a list of accounts with not only the account number, but also the currency represented by an icon or image of a country flag. Here is my current component setup: <select name="drpAccounts" class= ...

Steps to create a TypeScript function that mimics a JavaScript function

As I look at this javascript code: // find the user User.findOne({ name: req.body.name }, function(err, user) { if (err) throw err; if (!user) { res.json({ success: false, message: 'Authentication failed. User not found.' ...

In this guide, learn the best way to dynamically adjust image height to match the height of any device

I am trying to make sure that the image on the front page of my website fits the height of the screen or device, and resizes responsively without cropping when the device height changes. How can I achieve this? If you need a visual example of what I mean, ...