Learning how to access my CSS file using Express and Node.js

I am new to using express and node.js.

I am trying to develop my app, but for some reason, my style.css file is not being recognized and I am unsure why.

Initially, I attempted to use .scss files, but after researching, I discovered that it was not possible.

Therefore, I converted my style.scss file to style.css, but when I run my app, the styles are still not applied. In the inspector, I see the following message:

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

When I click on the link 'http://localhost:3000/style.css', I receive the following message in the tab:

Cannot GET /style.css

Here is my code in index.js :

const express = require('express'); 
const {engine} = require('express-handlebars');
const app = express();
const port = 3000;

app.engine('handlebars', engine({
    layoutsDir:__dirname + '/views/layouts',
}));

app.set('view engine','handlebars');
   
app.get('/', (req,res) => {
    res.render('main', {layout : 'index'})
});
app.use(express.static('public'));

app.listen(port, () => 
console.log(`Our app is running at : http://localhost:${port}`)
);

In my index.handlebars file, I have the following line:

 <link rel="stylesheet" type="text/css"  href="./style.css">

When I ctrl+click on "style.css", I can locate the correct css file.

Can anyone offer assistance?

Answer №1

if you are certain that the file style.css is located in the public directory.

The only issue remaining in your index.js script is the missing line

app.use(express.static('public'));
. Make sure to include it before rendering any pages.

Here's an example:

const express = require('express');
const {engine} = require('express-handlebars');

const app = express();
const port = 3000;

app.engine('handlebars', engine({
    layoutsDir:__dirname + '/views/layouts',
}));

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

app.use(express.static('public'));
   
app.get('/', (req, res) => {
    res.render('main', { layout: 'index' });
});

app.listen(port, () =>
console.log(`Our app is running at: http://localhost:${port}`);
);

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

The HiddenField is returning empty when accessed in the code behind section

In my gridview, the information is entered through textboxes and saved to the grid upon clicking a save button. One of these textboxes triggers a menu, from which the user selects a creditor whose ID is then saved in a HiddenField. <td class="tblAddDet ...

Encountered a URIError while trying to handle the request: Unable to decode

var express = require('express'); var app = express(); app.get('*', function (req, res) { var host = req.get('Host'); return res.redirect(['https://', host, req.url].join('')); }); var server = ap ...

Having trouble receiving a response from an API built using Express.js and SQL Server

Currently, I am in the process of learning how to create an API using Node and Express.js. I came across a step-by-step guide that has been very helpful. You can check it out here. I've followed the instructions provided and created a similar version ...

How to use AJAX script to call a non-static page method in ASP.NET

Is it possible to achieve this task without utilizing the UpdatePanel feature? ...

The JSON.stringify function encounters difficulties when trying to format an object into

Why does JSON.stringify refuse to format objects and keep everything on a single line? <!DOCTYPE html> <html> <head> <script> var obj = { "a" : "1547645674576457645", "b" : "2790780987908790879087908790879087098", "c" ...

Content in Bootstrap not filling entire mobile screen

The content in this form does not stretch to full screen on mobile phones, but it appears properly on computers and tablets. Please advise on how to solve this issue. https://i.stack.imgur.com/S2XkS.jpg <link rel="stylesheet" href="https://maxcdn.bo ...

Invoke the forEach method within a lambda function and assign the output to a variable

In order to achieve my goal, I am looking for a way to take an array as input and save the result for future use. Unfortunately, I do not have permission to create additional functions. As a result, the code must accurately reflect what result should be. l ...

Show a notification when utilizing AJAX requests

I consist of two separate files: one written in PHP and the other one in JavaScript and HTML. PHP file : <?php session_start(); //start session $_SESSION['data'] = "The content should be displayed as alert in the JS file"; JS/HTML File: & ...

Regular expression for identifying a specific attribute paired with its corresponding value in a JSON object

Below is a JSON structure that I am working with: 'use strict'; // some comment is going to be here module.exports = { property1: 'value1', property2: 999, }; I am looking to remove the property2: 999, from the JSON. I attempted ...

"Encountered an issue while trying to access the 'forEach' property of an undefined entity in Express

I encountered an issue when trying to post on an API built with Express.js and SQL Server DB. Fortunately, I discovered a solution that worked for me: const express = require('express'); const bodyParser = require('body-parser'); const ...

The functionality of the JavaScript animated placeholder seems to be malfunctioning

I am currently working on a code that updates the placeholder text every 2 seconds. The idea is to have it type out the letters one by one, and then erase them in the same manner. Unfortunately, the code is not functioning as expected. As a newcomer to J ...

What is the process for integrating an autoplay script into Turn.Js?

Can someone guide me on how to implement this code in Turn.Js? setInterval(function() { $('#flipbook').turn('next'); }, 1000); ...

AngularJS button click not redirecting properly with $location.path

When I click a button in my HTML file named `my.html`, I want to redirect the user to `about.html`. However, when I try using `$location.path("\about")` inside the controller, nothing happens and only my current page is displayed without loading `abou ...

The problematic max-width with srcset attribute

Here's the HTML markup I'm working with: <picture> <source srcset="img/home-page/placeholders/placeholder_2560.jpg" media="(max-width: 2560px)"> <source srcset="img/home-page/placeholders/placeh ...

What causes the return of undefined when accessing an item from an object?

In order to extract the item "Errors" from the data object provided below: {Id: 15, Date: "22-02-2019", Time: "22:45", Sport: "Football", Country: "United Kingdom", …} Bet: "Win" Bookie: "Bet365" Competition: "Premier League" Country: "U ...

What is the reason for the overflow occurring in a container of identical size due to this particular element?

I've encountered an issue while trying to create a div with a scrollbar that only appears when the elements within it don't fit the default area. <div style="overflow-y: auto; height: 36px;"> <img src="." width="36" height="36" /> ...

Issue when attempting to update user profile picture using Mongoose schema and Cloudinary

updateProfile: async function(req, res) { try { const update = req.body; const id = req.params.id; if (!req.files || Object.keys(req.files).length === 0) { return res.status(400).send('No files were uploaded.&a ...

Leveraging ng-switch with ng-repeat in AngularJS to dynamically apply HTML based on conditions

I have a paginated list of video thumbnails that I want to showcase in a Bootstrap fluid grid. To achieve this, I am utilizing a nested ng-repeat loop to iterate through each list for pagination purposes. Within the inner loop, another ng-repeat is used to ...

Retrieve every potential option of a dropdown menu

One of my tasks involves working with a select field that has various values: africa europe america asia oceania Whenever a value is selected, I aim to apply a specific CSS class to a particular div, with the name of the CSS class matching the selected v ...

Notifying users when a document is nearing its expiration date in the most effective manner

In my calendar app, I set appointments to automatically delete after 5 minutes. Now, I want to retrieve all appointments that are about to expire within 1 minute and send a notification to the front-end indicating their impending expiration. Although I at ...