How come I am unable to connect my CSS to my EJS files?

Having difficulty linking my css files to my ejs files. Using a standard node.js/express setup, I'm attempting to connect my main.css file from the public/css directory to my index.ejs file in views. The html and routing are functioning correctly. Please see below for the relevant section of my app.js code.

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');
var contact = require('./routes/contact');
var register_form = require('./routes/register');


var app = express();

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

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

In my index.ejs file, the link is placed between the head tags. All filenames have been verified multiple times for accuracy.

 <head>
    <title><%= title %></title>
    <link type="text/css" rel='stylesheet' href='../public/css/main.css' />
  </head>

Answer №1

Within your app.js file, you have properly set the location for your static files by using:

app.use(express.static(path.join(__dirname, 'public')));
. This configuration allows you to easily reference static files like css using absolute pathing starting from the public directory.

To ensure proper linking, update the line of code to:

<link type="text/css" rel='stylesheet' href='/css/main.css' />
and it will function correctly.

It is recommended to stick with this "absolute" pathing method as it ensures that your template pages can be moved around without breaking any css links (for instance, moving

views/index.ejs -> views/pages/index.ejs
).

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

When the last character in the route is a forward slash, the Express server will load the HTML page with CSS and JavaScript. Conversely, if the last route character

On my second html page model.html, I noticed the following issue: When I include a '/' at the end of my route address in the browser like this: http://localhost:3002/home/model/, the correct html page is loaded, but the css/js files do not load. ...

The FAB button animation is causing delays in the transition process and is not functioning as originally anticipated

I am facing an issue with the FAB button and 3 Icons. The functionality is working fine on click for both show and hide actions, but the transition is too delayed. I want the icons to appear step by step, even though I have adjusted the transition delay se ...

Why should one incorporate semantic markup into their HTML documents?

During my studies, I learned that tags provide a definition to content in HTML. For example: <section>It's a section</section> <article>It's an article</article> By correctly using semantic markup in my HTML, the documen ...

Is it possible to terminate an active server process triggered by an HTTP post request in Node.js prior to returning a response?

I developed an application where I utilized Ajax to make calls to a Node server. The issue is that even if the user navigates to another page, the server persists in processing the initial request made by the Ajax call. It then proceeds to process the new ...

Exploring how to verify passports on Node.js

Currently implementing authentication using passport in Nodejs as shown below: const passport = require('passport'); passport.use(strategies.jwtLogin); //using require('passport-jwt') const requireAuth = passport.authenticate('j ...

Is it normal for Node's console to not display all object properties?

After running some code, I noticed something peculiar. console.log(myURL); It seems that the extension property is missing: console.log(myURL.extension); However, when logging it on its own, the value appears correctly. The URL object was created ...

How can I use nodejs to export filtered data from dynamodb to a csv file?

I am looking to export specific data from my dynamodb database into a csv file. I have already written a function that filters the data based on name and id criteria. However, I am unsure how to proceed with exporting this filtered data into an Excel doc ...

Experiencing challenges with showcasing numerical values in the grid cells

My latest project involves creating an interactive sudoku solver. I've successfully created a grid made up of various elements to resemble an empty sudoku grid. However, my challenge lies in getting the numbers to display within the grid cells. Click ...

Utilizing JWT tokens for administrative and user authentication

I'm currently working with a system utilizing SPA (React) and JWT authentication (Node JS). I am trying to figure out the best way to determine the role of each user on the client side (such as admin, operator, etc) in order to render the appropriate ...

What is the correct way to run npm and node on Windows 11? I keep encountering an error when attempting to execute npm install on my Windows system

I am encountering an error message when attempting to execute npm install or npm install nodejs-java on my Windows 11 system. Here are the versions: npm version - 9.6.1 node version - v18.15.0 Visual studio - 2017 Despite multiple attempts, I have been u ...

How can I create a more spacious and stylish JTextField for my address bar?

I am working on developing my Java skills by creating a custom browser. Is there a way to adjust the size and shape of the address bar, which is currently implemented as a JTextField with Swing's default settings? Here is the code snippet I am using: ...

Tips for handling numerous buttons in ionic?

I'm currently working on an app that includes surveys. In this app, users are required to answer by selecting either the Yes or No button. The desired behavior is for the chosen button to turn blue once clicked, while the other button should maintain ...

php code to show data in a single column of a table

I am working with a database record that includes an id and name, and I need to display it in a table where records are distributed in the pattern 1-2-1-2-4 across columns. Below is my current code that is generating the incorrect output: <table borde ...

Divs sliding out of alignment

I am experiencing an issue with the scrolling behavior of a wrapper div that contains two nested divs. Specifically, when I scroll the wrapper horizontally on Android devices, the header section and content section seem to be out of sync and there is a not ...

How can I incorporate a custom color into a preset navbar on an HTML webpage?

<div class="navbar-header"> <button aria-controls="navbar" aria-expanded="false" data-target="#navbar" data-toggle="collapse" style="color: blue;" class="navbar-toggle collapsed" type="button"> <i class="fa fa-reo ...

Having issues with my CodePen React code and its ability to display my gradient background

I will provide detailed descriptions to help explain my issue. Link to CodePen: https://codepen.io/Yosharu/pen/morErw The problem I am facing is that my background (and some other CSS elements) are not loading properly in my code, resulting in a white bac ...

"Utilizing the flex box feature in IE 10 for efficient text trunc

.container { background: tomato; width: 100px; display: flex; } .text-left { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .text-right { } <div class=container> <div class="text-left"> title title title ...

Alter the path within a paragraph tag in html

I'm having some trouble changing the direction of a tag inside another tag. It's not working correctly for me. In the example below, I want to see aslami @ exactly as I have written it, but the result is showing @ before a instead of after i. ...

The Socket.io client establishes connections with multiple servers simultaneously

Imagine this scenario: I am using nodejs and socket.io, and a question comes to mind. What would happen if one client establishes connections with multiple servers like this: socket = io.connect('http://server1') //600k sockets already connecte ...

A beginner's guide to retrieving random names and images from JSON data for every object using JavaScript

I have a creative idea for a random ruffling game, where it picks a user's name and image randomly. However, I'm facing an issue with ensuring that each image matches the correct user when selected randomly. I want to make sure that every objec ...