What could be causing the CSS to not display properly on specific routes?

I'm facing an issue where CSS seems to be working fine for certain routes with node.js & express, but not for others. It's puzzling because the HTML file links to the same CSS file in both cases.

For instance, CSS works perfectly for the route "/feed", but fails to apply for "/users/:username". This is not an isolated incident and I am at a loss as to why this inconsistency exists. Any guidance on resolving this mystery would be greatly appreciated.

Let me provide a clearer illustration:

Index route (CSS functioning)

// @ROUTE: Home Route
// @DESCRIPTION: Renders the homepage
server.get('/', (req, res)=> {
    filesDB.find({}).sort({createdAt: '-1'}).exec((err, data) => {
        if(err) {
            throw err
        } else {
            res.render('Home.ejs', {
                pageTitle: "Feed :: ImgHub",
                curSession: req.session,
                images: data
            })
        }
    })
})

/users/:username route (CSS not working)

// @ROUTE: User Route
// @DESCRIPTION: Renders all the posts that were uploaded by the selected user
server.get('/user/:username', (req, res)=> {
    const username = req.params.username

    filesDB.find({'uploader': username}).sort({createdAt: '-1'}).exec((err, data)=> {
        if(err) {
            throw err
        } else {
            res.render('User.ejs', {
                pageTitle: `${username} :: ImgHub`,
                curSession: req.session,
                images: data
            })
        }
    })
})

Express static file setup

server.use(express.static(__dirname + '/CSS'))

Just to clarify, there are no error messages showing up in the console log while browsing the website.

Answer №1

It seems like the issue lies within your HTML setup

You have included your CSS file in this manner:

<link rel="stylesheet" href="styles.css">

If your URL is something similar to /feed, everything works fine. However, for links such as /something/here, the CSS file will be searched at /something/styles.css. To address this, ensure to specify the root by adding / to your CSS declaration like so:

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

This way, your styles will consistently be retrieved from the root directory which is /

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 process of updating MongoDB documents unexpectedly halted with an error code of 8000 and an identified name of 'AtlasError'. This issue was encountered while using the NodeJS driver in a web application

My NodeJS backend web app has been running smoothly for weeks, with the ability to read and write to my MongoDB cluster without any issues. However, today I encountered errors when attempting to update documents, even though I can still successfully retrie ...

Setting up a chat feature in a Laravel application: A step-by-step guide

Looking to Enhance My Web-Application I have been working on a web-application that utilizes: Laravel for the back-end Angular for the front-end. Milestone Achieved! I successfully implemented the entire user authentication process including: User Aut ...

Using the same function in two different locations will only work for one instance

I have an AngularJS application where I am using a function called foo(bar) that takes bar as a parameter. The data for bar is retrieved from a web API, and I loop through this data using ng-repeat which works perfectly fine. <li class="list-group-item ...

Using HTML and CSS to evenly align text in individual sections

Is it possible to recreate the exact look and feel of a justified page from a book or article online using HTML/CSS? This would include replicating the text justification with precise line breaks and setting the outer wrapper width to match the min/max-wid ...

Ways to access the POST request body prior to forwarding it through a proxy server

When using the connect library on Node.js, I attempted to retrieve the request body before proxying it using node-http-proxy. With Node.js version 4 and above, it is necessary to utilize middleware such as bodyParser (or handle the data/end events on the ...

Utilizing a sub-query in Sequelize to refine upcoming events by dates and times

Is there a way to query for an upcoming event using sequelize? I am looking for a solution where once an event has already started, it will be removed from the "upcoming events" column. I attempted to achieve this by: db.Event.findAll({ where: { ...

Generate Array of Consecutive Dates using JavaScript

My array contains the following values (for example): [ 1367848800000: true, 1367935200000: true, 1368021600000: true, 1368108000000: true, 1368194400000: true, 1368367200000: true, 1368540000000: true, 1 ...

Determining the pixel padding of an element that was initially set with a percentage value

I am working with a div element that has left padding assigned as a percentage, like so: padding-left: 1%; However, I need to obtain the value of this padding in pixels for some calculations after the window has been resized. When using JavaScript to chec ...

Troubleshooting inactive CSS hover animation

Greetings! I'm facing an issue with a CSS hover animation. Here are two demos I've created: In the first DEMO, the animation works perfectly. However, in the second DEMO, it doesn't seem to be functioning. On the second demo, there are two ...

Using CSS to showcase div elements with varying dimensions

How can I arrange divs with varying heights to be positioned close together, regardless of their height, and with a specific margin similar to buildings? I am aiming for a layout like the one on this website . I tried using float:left but it only float ...

Ways to implement a 'Delete' feature in a PHP audio tag player

"I successfully retrieved the name of the uploaded file and am able to play it in my browser. How can I incorporate a delete function for each user-uploaded song?" echo "<hr />"; echo "<h4>" . $name . "<br /><a href='#' titl ...

`Eliminate a few bbcodes in the code snippet`

I am currently experiencing an issue with a bbcode parser that converts to HTML. Whenever I try to parse the code, I encounter problems with tags that are not in my approved set by the parser. For instance: The parser only permits [b], [center], and [i] t ...

Is it time to switch out HTML tables for Divs?

I am looking for advice on creating a consistent header for all of my website pages. Currently, I use a div element to wrap a table that contains one row with three cells. These cells hold three images: one in the top-left corner, one in the top-center, a ...

What is the process for configuring a headless implementation of three.js on a node server, similar to the babylon.js-NulEngine setup?

My current project involves the development of a multiplayer three.js fps game, with client-side prediction in the browser. For the server-side implementation, I am utilizing Node.js Express.js and Socket.io for handling authoritative functions such as col ...

Changing a variable within a method does not automatically reflect in the child component

Need help with Vue update process for props/child components. Consider this component: <template> <v-card> <Modification v-model="newObject"></Modification> <OtherComponent @close="resetObject">& ...

How does a web worker behave when the owner is not actively engaged?

[edit: I am using Chrome 49.0.2623.112 m (64-bit) with default settings and HTTPS, but the issue occurred before the switch.] My application utilizes web workers to handle AJAX polling. While this may not provide a significant performance boost, it does e ...

Requesting a resource using the HTTP GET method returned no data

Looking to process the response from an http-request using JavaScript? Check out this straightforward example below. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html x ...

What is the best way to resize SVG graphics effectively?

I am in need of creating a seating chart. I have generated an SVG with the seats. <div class="seats-map"> <svg xmlns="https://www.w3.org/2000/svg" id="seats-map-svg" viewBox="0 0 1000 300"> <g data-row ...

Performing a simulated click on a dynamically inserted element using pure JavaScript

I am faced with the challenge of programmatically navigating a ReactJS-based website in a looped workflow. The process involves clicking on Element1, dynamically altering the web page to add Element2, then clicking on Element2, and so on until eventually r ...

The image tag in HTML is unable to display as an image within the jQuery object

After converting the object "suggestion" to a string, I have data stored in the "sugestion" variable like this: {"value":"<img src=\"http://localhost/erp/assets/images/product/123.jpg\"> 123123123 t-shirt","data":"ABC098765"} Unfortunatel ...