enhancing the style of my Express project with CSS and EJS

Currently, I am facing challenges with linking CSS to my EJS files in a project I am developing using Node/Express/EJS. Despite creating a public folder with a CSS subfolder and the main.css file inside, I am unable to get the CSS to display in the browser. I have followed tutorials to resolve this issue, but I am still struggling to find a solution. I would greatly appreciate any help with this matter :)

Here is my app.js file with the app.use

const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const mongoose = require('mongoose');
const passport = require('passport');
const flash = require('connect-flash');
const session = require('express-session');
const path = require('path');

const app = express();

// Passport Config
require('./config/passport')(passport);

// DB Config
const db = require('./config/keys').mongoURI;

// Connect to MongoDB
mongoose
  .connect(
    db,
    { useNewUrlParser: true ,useUnifiedTopology: true}
  )
  .then(() => console.log('MongoDB Connected'))
  .catch(err => console.log(err));

// EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use('/css', express.static(__dirname + 'public/css'))


// Express body parser
app.use(express.urlencoded({ extended: true }));

// Express session
app.use(
  session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true
  })
);

// Passport middleware
app.use(passport.initialize());
app.use(passport.session());

// Connect flash
app.use(flash());

// Global variables
app.use(function(req, res, next) {
  res.locals.success_msg = req.flash('success_msg');
  res.locals.error_msg = req.flash('error_msg');
  res.locals.error = req.flash('error');
  next();
});

// Routes
app.use('/', require('./routes/index.js'));
app.use('/users', require('./routes/users.js'));
app.use(express.static(__dirname + '/public/styles/main.css'));

const PORT = process.env.PORT || 5000;

app.listen(PORT, console.log(`Server started on port ${PORT}`));

This is the EJS file

<!DOCTYPE html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="description" content="">
        <script src="https://kit.fontawesome.com/4ab1675432.js" crossorigin="anonymous"></script>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>TBANK</title>
        <link rel="stylesheet" href="css/main.css">
    </head>
    <body>
      <header>
          <div class="logo">
              <h1 class="logo-text"><span>T</span>BANK</h1>
          </div>
          <ul class="nav">
              <li><a href="#">Savings</a></li>
              <li><a href="#">Borrowing</a></li>
              <li><a href="#">Features</a></li>
              <li><a href="#">Sign Up</a></li>
          </ul>
      </header>
      <div class="main-body">
        <div class="home-heading">
          <h1 class="home-header">Bank with the future</h1> 
        </div>
        <!--<div class="container"><%- body %></div>-->

<div class="footer-container">
    <footer class="footer_area">
      <div class="row">
        <div class="column">
          <span>T</span>BANK
        </div>
        <div class="column">
          <ul class="list-style-company">
            <li><a href="#">About us</a></li>
            <li><a href="#">Careers</a></li>
            <li><a href="#">Press</a></li>
            <li><a href="#">FAQS</a></li>
            <li><a href="#">Terms & Conditions</a></li>
          </ul>
        </div>
        <div class="column">
          <ul class="list-style-company">
            <li><a href="#">Community</a></li>
            <li><a href="#">Transparency</a></li>
            <li><a href="#">How money works</a></li>
            <li><a href="#">How we protect you</a></li>
            <li><a href="#">Business Accounts</a></li>
          </ul>
        </div>
        <div class="column">
          <div class="f_social_icon">
            <a href="#" class="fab fa-facebook"></a>
            <a href="#" class="fab fa-twitter"></a>
            <a href="#" class="fab fa-instagram"></a>
          </div>
        </div>
        </div>
      </div>
    </footer>
    </body>
</html>

Answer №1

To start, make sure to confirm that your CSS is loading correctly on the specified URL. Check your browser to ensure that the CSS is served without any issues at the address http://localhost:8080/css/main.css

If the CSS is loading properly, then the issue likely lies with the path to the CSS in your HTML. If it's not loading correctly, there may be a configuration problem or it could be located at a different URL.

It seems probable that the URL css/main.css (relative to the current page URL) should actually be /css/main.css (relative to the root of your application).

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

What is the best way to retrieve information stored in objects with ejs?

I am currently passing data from my app.js file to my ejs files in this format: { _id: 2500, firstName: 'John', lastName: 'Doe', comments: [ { _id: 5555, title: "Hello", comment: "Hello, World" } ], __v: 0 } By using a forEach loop, I ...

Text on Bootstrap buttons does not adapt to different screen sizes

https://i.sstatic.net/9Hc9w.png I've been struggling to make the button text responsive, but all my attempts have failed. Below is the HTML code I've been using: <button style="margin-top : 5px;" type="submit" class="btn btn-primary ...

Changing selections in jQuery may not work properly on certain mobile and IE browsers

I am currently working on creating a dependency between two select boxes. The jQuery code I have implemented works perfectly on most common browsers such as Chrome and Firefox, but it seems to have some issues with Internet Explorer, Edge, and some mobile ...

Angular: How to Disable Checkbox

Within my table, there is a column that consists solely of checkboxes as values. Using a for loop, I have populated all values into the table. What I have accomplished so far is that when a checkbox is enabled, a message saying "hey" appears. However, if m ...

What steps can be taken to successfully execute a Nodejs project when encountering an error message such as "Unresponsive script"?

When I try to run my Nodejs project, I encounter an error message stating "Unresponsive script". I came across a project on GitHub called angularjs-rickshaw. This project is built on Nodejs and bower. Project: ngyewch/angular-rickshaw Demo of the projec ...

Unable to display <div> elements from CSS within the Wordpress Text Widget

Having trouble displaying a <div> from CSS in a Text Widget on Wordpress. <div class=”deffgall-cutlure” ></div> style.css .deffgall-cutlure { display:block; position:relative; width:100px; height:100px; backgrou ...

Can someone explain to me the meaning of "var vm = $scope.vm = {}" in AngularJS?

While reading through the angularJS api, I came across some code that looked like this: myApp.controller('MyController', ['$scope', function($scope) { var vm = $scope.vm = {name:'savo'}; } ]); Initially, this mul ...

What are some ways to display unprocessed image data on a website using JavaScript?

I have an API endpoint that provides image files in raw data format. How can I display this image data on a website using the img tag or CSS background-image property, without utilizing canvas? One possible approach is shown below: $.get({ url: '/ ...

When querying for a specific document in mongoose using findById,

I am currently working on a task management application where I have encountered an issue. When trying to move a task from the to-do list to the done list, the methods "columnId" and "findById" are returning null values. Can you offer any insight into wh ...

What is the best way to organize controls on my website?

My web page controls need to be organized in the specific layout below: Header Left Content - Main Content - Right Content Footer Is there a control available that can assist me with achieving this layout? I prefer not to use a table since it may not b ...

I receive an [object HTMLCollection] as the output

I am currently working on recreating a login page and I want it so that when the button is clicked, it displays the name you entered, but instead, it returns [object HTMLCollection]. My expectation was to have the name displayed as entered. var nombre ...

Attaching an Event Listener to an array

I am struggling with a homework assignment and don't understand why I am receiving an error message saying 'undefined is not an object (evaluating 'buttons[i].style')). Any help would be appreciated. I have been attempting to loop throu ...

Completes a form on a separate website which then populates information onto a different website

Creating a website that allows users to login and view various complaint forms from government websites or other sources. When a user clicks on a link to file a complaint, they will be redirected to the respective page. However, I am looking for a way to ...

"Exploring Angular: A guide to scrolling to the bottom of a page with

I am trying to implement a scroll function that goes all the way to the bottom of a specific section within a div. I have attempted using scrollIntoView, but it only scrolls halfway down the page instead of to the designated section. .ts file @ViewChild(" ...

Encountering unregistered model error while attempting to populate data from MongoDB in Next.js

Within my application, I have 3 models: USER, CATEGORY, and PRODUCT. The product model contains two fields that reference the other two models. When attempting to populate data, an error is thrown stating that users are not registered, and the same for cat ...

Exploring the wonders of Node.js, Redis, and Express.js while navigating through the enchanting world of Asynchronous

Hello there, I must confess that this is a whole new realm for me... Here is what we've got: app.get('/user/:user_id/followings', function(req, res) { var response = {} , userId = req.params.user_id , ids = req.param(' ...

Express.js Node - Retrieve file from memory - 'filename parameter must be in string format'

My aim is to package data stored in memory into a text file and deliver it to the user for download. However, I am encountering an issue with the following code: app.get('/download', function(request, response){ fileType = request.query.fil ...

The object THREE.DRACOLoader does not have a constructible function

When importing the three js and draco modules as shown below: import * as THREE from 'https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e7938f958282a7d7c9d6d5d6c9d6">[email protected]</ ...

Can templates be nested within other templates using different contexts?

I am in the process of developing an application using nodejs and handlebars. My goal is to create a layout template and insert various individual components into that layout. Each component will have its own handlebars template and context. e.g. layout. ...

Animating all the numbers on a jQuery countdown timer

http://jsfiddle.net/GNrUM/ The linked jsfiddle showcases a countdown of 2 seconds, with only the numbers displayed. My goal was to explore: a) How can I incorporate animations into the JavaScript code so that the number changes in size, color, and positi ...