Using Node.js and Express, the CSS does not load due to route parameters

I'm currently working on a basic website project using Node.js, Express, and the EJS template engine. I've run into an issue where my external CSS files are not loading properly on routes that contain route parameters. Here's a snippet of my code:

const express = require("express");
const app = express();
var AWS = require('aws-sdk');
var uuid = require('uuid');
var request = require('request');
var Amplify = require('aws-amplify');
const { info } = require("console");

app.use(express.static("public"));
app.set("view engine", "ejs");

app.get("/Test1/", function(req, res){
res.render("Test1.ejs");
});

app.get("/Test2/:route", function(req, res){
res.render("Test2.ejs")
});

Both Test1.ejs and Test2.ejs are basically identical copies of each other, one being duplicated from the other.

The problem arises when the CSS file loads perfectly fine on Test1 but fails to load correctly on Test2. Instead, Express serves the HTML content of Test2.ejs in place of the intended CSS file. This discrepancy occurs without any changes or reloads. The situation is puzzling because the CSS works flawlessly on all other routes except for those with route parameters. To troubleshoot, I have even tried incorporating the route parameter directly as follows:

app.get("/Test2/:route", function(req, res) {
const routeParam = req.params.route;
res.render("Test2.ejs", {
    routeParam: routeParam
});

});`

Although I verified that the routeParam displays correctly on the page, the issue persists with the page rendering the HTML instead of the expected CSS file, resulting in improper formatting.

If anyone has insights or suggestions on resolving this matter, I would greatly appreciate it. Thank you!

Answer №1

Thank you CoderFF for your help in solving this issue and showing me how to make it work. It turns out that the problem was caused by my css file being directly placed inside the public folder, instead of within a subdirectory inside it. The correct structure should be like this:

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

Make sure to include the leading '/' in the href tag. I am unsure how it was functioning properly for me previously without this on routes without parameters, but it somehow was. The same principle applies to images located in an /images/ folder inside the public directory.

Answer №2

I'm having trouble replicating this issue. Here is what I have tried:

  1. I added my CSS to a file called public/css/all.css. The file contains just one line: html {background-color: #aaaaaa}, so I can confirm it's being loaded.
  2. I created two templates, named views/Test1.ejs and views/Test2.ejs, with the same content:
    <html><head><link rel="stylesheet" type="text/css" href="/css/all.css"/></head><body></body></html>

Everything is working smoothly on my end.

It seems like you might have created a folder named Test2 inside your public/ directory, where you placed your CSS files. If that's the case, the path to your CSS file would be /Test2/some.css, which matches your second route. This could be causing the server to serve HTML instead of the CSS file.

To resolve this issue, consider moving your CSS files accordingly.

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 Font Awesome icon is not displaying on top of the Materialize CSS progress/determinate bar

I am struggling to display a Font Awesome icon on top of a Materialize CSS progress/determinate div. Unfortunately, the icon is not fully visible and part of it gets clipped or hidden. Despite trying various solutions, I have not been successful. .progres ...

Methods for incorporating rtl functionality into Angular Chosen

I am currently using Angular with Chosen (source) and I am attempting to implement right-to-left (RTL) support. Here is my demo, but despite referencing resources, I am encountering issues. The main problem arises when the body element has a dir="rtl" att ...

Imagine the scenario where unwind is used on a field that does not exist when utilizing aggregation in mongoose - what outcome can be expected?

Imagine I'm utilizing a $unwind on a field in mongoose schema. As per the link provided, if the field is missing, $unwind will disregard the input document. How can I prevent this from happening so that the query result is returned without unwindi ...

Is it possible to retrieve the IMEI number of a mobile phone using expo?

Currently working on developing a mobile app with React Native using Expo. I need to figure out a way to access the client's mobile IMEI number and display it in the front end of the app. Unsure of how to accomplish this task. Is there a method to do ...

Unable to establish connection with mongodb-atlas database

Struggling to establish a connection with the free MongoDB database on mongodb-atlas. I've exhausted all options - checked the documentation, updated the URL, changed passwords, and even created a new user from scratch. Yet, the issue persists. Here ...

Testing BigQuery queries in Node.js

As a beginner in writing mocha unit tests, I am seeking guidance on how to create a unit test for the code snippet below, particularly focusing on the BigQuery aspect. The code is designed for a PubSub triggered Cloud Function that inserts rows into a BigQ ...

The fieldset css in PrimeNG differs from the website's original design

On my website, the appearance of the fieldset can be seen here: https://i.stack.imgur.com/TTS8s.jpg. I did not make any CSS changes that altered the fieldset. I am utilizing primeNG v7 and Angular 7. <p-fieldset legend="Toggleable" [toggleable]="true" ...

Using Multiple SCSS Files to Reference a Centralized Style Sheet

I am currently developing a React application and facing an issue with my SCSS files. I have three SCSS files, one main file that contains theme variable colors, and the other two are located in component folders. When I import the main SCSS file into the ...

Having trouble making a basic delete request in Postman

Looking for assistance with a phonebook app built using node.js, express, mongo db, and mongoose. Currently, Get and Post requests are functioning properly, with Post requests being saved in the Mongo database. However, encountering issues with Delete re ...

Webpack configuration for asynchronous loading

I'm having trouble making this work. Can someone please assist? :) (According to the documentation, webpack is capable of handling Promises) Here is what works for me: var compiler = webpack(webpackConfig) However, when I try using a promise, I en ...

Switching from real pixels to CSS pixels

The details provided in Mozilla's documentation on elementFromPoint clarify that the coordinates are specified in "CSS pixels" rather than physical pixels. This raises a question about what exactly CSS pixels entail. Many assume that a pixel in CSS is ...

Instructions on triggering a pop-up modal from a separate HTML document to the index page

I am trying to open a form in a Modal using a button. However, the Modal is located in a separate .html file. How can I use JavaScript to call the form from that external html file into my index.html file? Currently, I am able to call the Modal within the ...

Terminating the user's passport session

Having a react front end and node/express/passport backend, I currently have an endpoint that returns the req.user object. router.route('/userauth') .get(authHelpers.getAuthUser) I also have a logout endpoint set up like this: router.route(& ...

Centering text both vertically and horizontally over an image using CSS

I've been attempting to center the div banner_title both vertically and horizontally within another div in this way... .box { text-align: center; } .banner_title { font-size: 32px; position: absolute; top: 50%; width: 100%; } .banner_titl ...

Error in the code that I am unable to locate in JavaScript, HTML, and CSS

I need help creating a navbar that displays the active site using HTML and JS code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content=& ...

Adjust the background color as you scroll

I am looking to create a functionality where the background-color of my header changes to match the background-color of the div it is currently scrolling past. For example, if the user scrolls to the #about section (which has a green background), I want th ...

The input-group-btn is positioned to the right of the field, appearing to float

The input-group-btn for the targetDate field remains fixed on the right side of the input group despite screen width variations until I introduce the automatically generated CSS from the hottowel generator. I require assistance in identifying which aspect ...

What is the best way to create a navbar with a grid that spans the full height and includes two rows

My approach to structuring the layout using CSS grid is as follows: nav content nav footer This means that the 'nav' will occupy the entire height of the page with a specified width, and the remaining space will be divided between the 'cont ...

Having trouble with the mouse trail code on codepen.io

I am currently attempting to integrate this specific CodePen sample into a Hugo template called Somrat Theme. I'm facing challenges in deciding where to place the HTML file; only the 'no cursor' section should go into style.css, and I need ...

Error 502 is being returned by the Nginx server for specific directories within the Express Application

Currently, I have an express application running on Ubuntu with nginx as the web server. Everything was functioning correctly until today when I attempted to add two new directories using the app.get method and re-deployed my app. Unfortunately, the new ...