Issue with loading CSS file in ejs template

Help Needed - I'm struggling to understand why the CSS file is not loading in ejs. The terminal isn't showing any error message, but it's displaying this message: "GET /assets/css/style.css 404 159 - 0.674 ms". My server (localhost) is running perfectly fine.

What I've Tried: I have used app.use(express.static(__dirname + '/assets/css')); which resulted in the same message. I also experimented with changing file paths and tried other methods, but nothing seems to be working.

My ejs code:

const express = require('express');
const dotenv = require('dotenv');
const app = express();
const morgan =require('morgan');
const path = require('path');
dotenv.config({path:'./config.env'});
const PORT = process.env.PORT ||8080

// parse request to body-parser
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// log request 
app.use(morgan('tiny'));

// set view engine 
app.set("view engine","ejs");
app.set("views",path.join(__dirname,"views"))

//load assets
app.use('./css',express.static(path.resolve(__dirname,"assets/css")));
app.use('/img',express.static(path.resolve(__dirname,"assets/img")));
app.use('/js',express.static(path.resolve(__dirname,"assets/js")));
app.use(express.static("assets"));

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

app.listen(PORT,()=>{console.log('Server is running successfully');});

_header.ejs File

<html>
    <head>
        
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous"/>
    
        <link rel="stylesheet" type="text/css" href ="/assets/css/style.css">
</head>
    <body>
 <!----HEader-->
    <header id="header">
<nav>
    <div class ="text-center">
      <a href ="/" class ="nav-brand text-dark">User Management System</a>
    </div>
</nav>

    </header>
File structure:
-assets
--css
---style.css

Answer №1

Utilizing app.use enables the addition of global middlewares to your routes.

The syntax is as follows :-

app.use('/someEndpoint', middleware);

Rather than ...

app.use('./styles', express.static(path.resolve(__dirname, "assets/styles")));

//styles/main.css
app.use('/images', express.static(path.resolve(__dirname, "assets/images")));
app.use('/scripts', express.static(path.resolve(__dirname, "assets/scripts")));
app.use(express.static("assets"));

Consider using ...

app.use(express.static(path.join(__dirname, "assets")));

This will serve the entire assets directory on the internet.

The specified line of code will serve the contents of your assets directory including ALL its contents for every route current and future ones.

Since the assets directory is already being served, there is no need to include assets in the href within your <link> tag.

The css file path is assets/styles/main.css.

Prior to this update, the server was looking for assets/assets/styles/main.css after serving up assets.

In your _header.ejs file, modify the href of your link to:-

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

Now the server will search for assets/styles/main.css, preventing any errors.

This explanation should clarify things.

I am unsure about the purpose behind these lines of code ...

app.use('./styles', express.static(path.resolve(__dirname, "assets/styles")));
app.use('/images', express.static(path.resolve(__dirname, "assets/images")));
app.use('/scripts', express.static(path.resolve(__dirname, "assets/scripts")));

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

Firefox Misplacement: Erroneously Shifting Element Locations

I have recently completed designing and developing a new website, which you can visit here. However, I am currently facing an issue with the positioning of the "About Us" image when accessing the site on either a tablet or a mobile device. Strangely enou ...

Encountered a deployment issue when configuring AWS Elastic Beanstalk for Node.js React application: "babel: command

Struggling to deploy a React Node app on Elastic Beanstalk and encountering server-side errors Here is my folder structure: -client -server - index.js - other files, etc. -package.json My package.json scripts are set up as follows: { "version& ...

The Socket.io application is facing deployment issues on the Heroku platform

I have developed a simple chat server using nodejs, socket.io, and express, and now I am attempting to deploy it on Heroku using my Git repository. However, when I access the Herokuapp website for my application (), the display is not as expected: https:/ ...

Sorting through a table based on the name of the element

I am currently working on filtering an HTML table using a search form. It's working great, but I'm facing an issue where the filtered elements are trying to fill the entire width of the table instead of maintaining their original width (which is ...

Redis data retrieval is successful on the second attempt

I am utilizing a Redis database along with express routing to create an API. My stack includes node.js and ioredis as well. The process involves connecting to Redis, fetching keys related to a specific date, and then retrieving the data associated with th ...

An element in CSS that has a position of fixed and a width of 100% surpasses the dimensions of its

My element has the CSS properties position:fixed and width:100%, causing it to be larger than its parent elements. Despite the complexity of my code, I have attempted to simplify it for better understanding. Below, you can see that the green box exceeds ...

Issue: The module '[object Object]' could not be located

const express = require('express'); const app = express(); const jade = require('jade'); const path = require('path'); const server = require('http').createServer(app); const io = require('socket.io').liste ...

Signs that indicate you have reached the bottom of the page

Wondering how they achieve that cool effect on where the top line appears with a new logo when you scroll down? Is it done using a jQuery trick? How can you determine when a person has scrolled down a certain amount of pixels and then show them new HTML ...

When using JSON.stringify in Node JS, the serialization process may fail to properly handle arrays of

I have been exploring the capabilities of sails.js, a node js framework. Currently, I am facing an issue with JSON.stringify where one of the fields (rooms array) is being omitted from the output. When I check the object using console.log, here is what I ...

Issues with Bootstrap's navbar-toggleable-sm functionality not functioning properly

Just started learning Bootstrap and following a tutorial on Lynda.com about customizing the navbar. However, despite following the tutorial step by step, my navbar is not behaving as expected - it's stacking vertically on all device sizes instead of j ...

management in the same row or in the following row fashion

Looking to achieve a specific behavior for a label and control: If the screen width is less than X, the label and control should be on different rows with the control expanding to full width. If the width is equal to or greater than X, the label and cont ...

Creating a Google Action with Node.js: A Step-by-Step Guide

I'm a beginner in Google Actions development and I'm wondering how to create a new Google action using node.js. I already know how to do this with Dialogflow, but I'm not sure how to create the app.js file for the Google Action. Can someone ...

the div background is limited to the exact size of the text, not filling the entire

Currently, as I work on my web page using react.js, I'm facing the challenge of implementing a full-size background. Despite my efforts, the background only occupies the size of the text within the div. Here is the snippet of code I am working with: a ...

Comparing two arrays containing 10 million items shows that _.difference function is not efficient enough

I am facing a challenge with two arrays containing user ids that I need to compare. arr1 = [123, 456, 789]; arr2 = [123, 456, 789, 098]; The issue is that these arrays can be quite large, sometimes containing up to 10 or 20 million items. I have attempt ...

The data-bs-theme attribute of an element does not take precedence over the global theme

UPDATE: I recently included a placeholder item in my carousel because the local database feed was not working, and now the theme is malfunctioning locally as well. Something seems off with the carousel items causing issues. END OF UPDATE I successfully ...

"Reasons Why I'm Unable to Retrieve the Length of an Array

Can someone lend a hand with finding the array length? I attempted to utilize Object.keys for this task { "@odata.context":"https://graph.microsoft.com/v1.0/$metadata#sites('volagas.sharepoint.com')/sites('volagas.sharepoint.com%2C9 ...

Troubles arising when trying to import a CSS file into a React Component without resorting to

https://i.sstatic.net/fNEuU.png After exploring the latest version of create-react-app, I discovered that there is no need to use the "npm run eject" command. When I tried that in the past, I struggled to locate the webpack.js file for modifications. htt ...

Attempting to retrieve tasks for the currently logged in user using Node.js in conjunction with MongoDB

I am currently working on a project that involves assigning tasks to different users, with each user only able to see their own tasks. To achieve this, I have implemented a system where the user ID is used as the key. When a user logs in, a token containi ...

Server up and running smoothly, no errors detected but experiencing functionality issues

I'm facing an issue where Grunt isn't showing any errors, but when I visit the IP address, nothing appears on the screen. I have confirmed that Node is functioning correctly because I created a simple server using Node which runs on the same por ...

What steps do I need to take to integrate blockchain technology and develop a public ledger for my specific application

I am currently in the process of developing a nodejs application that includes blockchain integration. Specifically, I am looking to create a blockchain within my application where only the server (my app) has the ability to generate blocks. The goal is to ...