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

A step-by-step guide on setting up a basic Node server to enable Gzip compression for static files

I've been at this for hours... Initially, I followed a tutorial on Node.js and Express for serving static content. The code provided was: var express = require('express'); var app = express(); // New call to compress conten ...

The output of Node.js `crypto.final` differs from that of PHP `mcrypt_encrypt`

Initially, Developing with Node.js Crypto. // Keeping key and IV hidden for privacy reasons. var secretKey = new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), // 48 characters iv = new Buffer('bb ...

The issue of ERR_MODULE_NOT_FOUND in Node.js express.Router arises when attempting to import new routes

Something strange is happening. I was in the process of organizing my routes by creating a new folder. Within this folder, I used the express.Router API to define the routes and then exported the router itself. Here is an example code snippet from my pos ...

Issue with Node 16: npm refusing to accept a trusted self-signed certificate

When attempting to run npm install while behind a proxy that intercepts HTTPS connections with a custom CA certificate, there was an issue. This occurred while using Node 16. Each time the command is executed, it fails with the following error: 3023 error ...

Issues with Cloud Foundry SSH functionality

I am encountering difficulties with SSH connectivity. I have verified that SSH is enabled at the Application and Space level. However, when I execute cf ssh "MY-APP-NAME", I encounter the following error: FAILED Error: SSH session allocation failed: s ...

What causes inline-blocks to malfunction after a non-breaking space is inserted?

Here is some HTML code: <p id='one'>Hello World how are you.&nbsp;<span>Entrepreneur</span></p> <p>Hello World how are you.&nbsp;<span>Entrepreneur</span></p> Below is some CSS styling: ...

What could be causing my MERN / Passport User Login to fail to redirect upon successful login?

Despite providing the correct login information, there is no response. No error messages or redirection occur. router.post("/login", (req, res, next) => { passport.authenticate( "local", { successRedirect: "/dashboard" }, (err, user, done ...

Headers cannot be set once they have already been sent in an express js application

After reviewing various responses to this query, I am baffled as to why this error keeps appearing despite having res.send() in multiple paths. In my code (expressjs 4.13), it looks something like this: var user ={ username: "some", password: "a" ...

Creating a Mongoose model with an array property that includes instances of the same model as the parent

My current challenge involves creating a Note object with a subnote property that should be of the same type as the parent model. Currently, I have achieved this by creating two identical models with different names and having them reference each other. He ...

Tips for accessing session variables post redirection in Node.js

Having an issue here. After setting a session and creating this object: req.session.userId = user.id But upon redirecting to another page, the userId object is suddenly undefined. I've read that this is due to the redirect process. Are there any sug ...

Is there a method to consistently keep the horizontal scrollbar in view for the MUI Data Grid at all times?

I have a Data table with virtualized columns, totaling more than 25 in number. Users can easily scroll horizontally using a trackpad, but without one, they may struggle to access all the columns due to the delayed appearance of the scrollbar. Is there a w ...

Is there support for TypeScript in express-openid-connect?

Is there any documentation available for using express-openid-connect with TypeScript, or if it is supported at all? ...

Having difficulty removing the node_modules directory

I am attempting to remove the node modules directory from my project in order to reinstall npm i because I encountered errors while running npm scripts (I suspect node_modules corruption), but unfortunately, I am unable to do so. My attempts include: Try ...

Change the border color of a form field in a material design if the user interacts with the

Is there a way to change the border color of a material form field in Angular when it is touched, focused, or active? I attempted to modify the color by overriding material css-class and also tried creating my own css class, but neither method had any ef ...

Understanding the relationship between CSS height and line-height can help developers create more

Is there a way to use CSS to set the height of a box based on its own line-height or its parent's line-height? This feature would make it much simpler to create text areas that are a specific multiple of lines, for example, displaying exactly three l ...

Error encountered in Express.js application with nginx configuration while serving static files from a subdirectory

upstream app { server localhost:3000; } server { ... # The dilemma I'm facing location ~* \.(?:jpg|jpeg|png|gif|swf|xml|txt|css|js)$ { expires 6004800; add_header Pragma public; add_header Cache-Control " ...

The CouchDB (nano) system may intermittently generate the message, "Unauthorized access to this database is prohibited."

After successfully implementing user authentication that returns a JWT in a cookie, I encountered an issue. Even though the request to establish a connection to the database is public and unprotected, I am getting a 403 error after logging in as a user. T ...

Generating a new page in PDFkit with additional content

My challenge lies in generating a PDF with data retrieved from the database. Everything works smoothly until there is an overflow of data that cannot fit onto the first page. How can I automatically create a new page when the current one is full and contin ...

Is it possible to configure node js to send an array instead of a string?

How can I modify the code to return a 2D array of the results? For example: clothes = [[1, "name", "desc"], [2, "name2", "desc2]] Can the 'res' variable send a list directly or do I need to create a list after returning it? app.get('/post&ap ...

Flexbox properties are being ignored by input fields

Hey there, I'm currently working on a product calculator and need to create 9 input fields organized in 3 rows of three columns. However, when I try to use display: flex and flex-direction: row on the parent div, it doesn't seem to be working as ...