Issue: CSS breaking in Node.js Express app when navigating with multiple child paths or parameter paths in the route.Description: Encounter

When attempting to load a page like /patient_profile, the CSS loads correctly. However, when continuing the path to

/patient_profile/settings_patient_profile
, the CSS breaks. Both pages mentioned are the same file, just testing the routing.

The route is managed as follows:

route('/patient_profile/:id')

route('/patient_profile/settings_patient_profile/:id')

I do reach the desired page, but the design elements do not work.

Another post suggested setting a static route with express to assets could fix the issue, but it didn't work for me. Perhaps I misunderstood how to correctly use the static path.

This directory tree structure:

.
├── docs
├── LICENSE
├── package.json
├── package-lock.json
├── README.md
├── src
│   │   ├── bootstrap
│   │   |   ├── css
│   │   |   |   └── bootstrap.min.css
│   │   |   └── js
│   │   |       └── bootstrap.min.js
│   │   ├── css
│   │   |   ├── FontAwesome.css
│   │   |   ├── font-awesome.min.css
│   │   |   ├── Footer-Basic-1.css
│   │   |   ├── Footer-Basic.css
│   │   |   ├── Login-Form-Clean.css
│   │   |   ├── Navigation-with-Button.css
│   │   |   ├── Registration-Form-with-Photo.css
│   │   |   └── style.css
... (omitting some files for brevity)

Omitted fonts and images to improve readability of the tree.

index.js

const express = require('express')
const routes = require('./routes/route')
const appPort = process.env.PORT
const app = express()

//.env
require('dotenv').config({
  path: path.join(__dirname, './.env')
})

//Setting up Handlebars
app.set('view engine', 'ejs')
app.set('views', __dirname + '/views')
app.use('/src', express.static(__dirname + '/src'))
app.use('/views', express.static(__dirname + '/views'))
app.use('/fonts', express.static(__dirname + '/fonts'))
app.use('/js', express.static(__dirname + '/js'))
app.use('/img', express.static(__dirname + '/img'))
app.use('/assets', express.static(__dirname + '/assets'))
app.use('/', routes)

//Creating a connection
app.listen(appPort, () => {
  console.log(`App is running. serve at port: ${appPort}`)
  console.log(`http://127.0.0.1:${appPort}`)
})

Sanitized programming related to DB etc.

My css reference in settings_patient_profile.ejs:

<link rel="stylesheet" href="../assets/bootstrap/css/bootstrap.min.css">
<link href='http://fonts.googleapis.com/css?family=BenchNine:300,400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="../assets/fonts/fontawesome-all.min.css">
<link rel="stylesheet" href="../assets/fonts/font-awesome.min.css">
<link rel="stylesheet" href="../assets/fonts/fontawesome5-overrides.min.css">

Answer №1

To ensure your CSS files work consistently regardless of the parent page's path, it is essential to use absolute URLs for the CSS links instead of relative links. Begin the link with / rather than ../.

Although the exact location of the target CSS files in your server file system is not specified, it seems necessary to make this adjustment:

<link rel="stylesheet" href="../assets/fonts/fontawesome-all.min.css">

Change it to something like this:

<link rel="stylesheet" href="/assets/fonts/fontawesome-all.min.css">

Then, utilize a single express.static() middleware that serves all content within the assets directory:

app.use('/assets', express.static(__dirname + '/assets/src'));

This specific suggestion is based on the assumption that all assets reside in /assets/src on your server disk.

Furthermore, by prefixing all static URLs with /assets, there is no need for individual handlers as they can all be managed by the preceding express.static() middleware:

app.use('/src', express.static(__dirname + '/src'))
app.use('/views', express.static(__dirname + '/views'))
app.use('/fonts', express.static(__dirname + '/fonts'))
app.use('/js', express.static(__dirname + '/js'))
app.use('/img', express.static(__dirname + '/img'))

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

Can a string variable be passed as a file in a command line argument?

Running a command line child process to convert a local file to another format is something I need help with. Here's how it works: >myFileConversion localfile.txt convertedfile.bin This command will convert localfile.txt to the required format an ...

Limit how API call costs are set in a function by throttling based on an argument

I am currently implementing express-throttle to restrict the number of API calls per IP address each day. I would like to dynamically set the 'cost' parameter in the 'options' array based on a value from the API request (refer to commen ...

Building adaptable divs using bootstrap technology

I'm playing around with bootstrap and here is the code I came up with: <!doctype html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet ...

A tiny blue spot popping up beside the roster of users

I'm working on a render function that displays a list of users with avatars and names. The issue I'm facing is that when the page initially loads, there's a blue dot to the left of each user. However, if I navigate to another page and then g ...

Arrange outcomes according to a category in a separate table

My database consists of two tables - 'products' and 'variants.' The 'variants' table has a field 'product_id' linking to a product in the 'products' table, along with a 'price' field. I am utiliz ...

I encountered an issue while attempting to secure the key with node-redlock, as it results

I need to lock the key called "ProjectData:GSTest" that is currently stored in a redis database. Below is the code I am using to achieve this, but it is throwing an error. Can someone please help me identify what is wrong here? const redlock = new Redlock( ...

Discovering WebElements nested within other WebElements using WebdriverJS

Looking at this HTML structure <div> <div> <p class="my-element"></p> </div> <div> <div> <div> <p class="the-text"> I want to retrieve this text</p> </div> </div> <div> ...

What are the steps to activate the hot-swapping feature for HTML and JavaScript files in IntelliJ's Community edition?

Just starting out with IntelliJ to work on an AngularJS project with spring-boot as the backend server. Every time I make changes to my HTML or JavaScript code, I find myself needing to restart the app server. Is there a configuration setting or plugin ava ...

Struggle transmitting information using Express.js and MongoDB

While trying to post data using Postman to localhost:3000/send-data, I encountered an error related to Body-Parser. Despite attempting to resolve it with express.json(), the issue persisted. Additionally, what is the most straightforward method for posting ...

The request body doesn't meet the interface requirements, but it does not trigger an error response

I created a specific interface called NewTransactionPayload to ensure that only objects of this type are accepted in the request body. Strangely, TypeScript does not show any errors when I host the application. Why is that? // Sample interfaces interface ...

CSS code preventing hyperlink from functioning

My website is almost complete, but I'm running into an issue with some hyperlinks on my event registration page. The first link works fine, but the second one does not. To troubleshoot, I created a test page with just the two links and still encounter ...

What is the best way to restrict the length and number of lines in a textarea based on pixel dimensions?

I am looking to create a textarea where people can select different fonts, such as "sans-serif" and "serif", to type in text. I plan to have buttons labeled "sans-serif" and "serif" that will change the font of the textarea when clicked. However, there ar ...

Mixing two elements for a continuous animation without the use of JavaScript

I'm interested in creating an animation that cycles between "0% interest free credit" and "free delivery". I am attempting to achieve this without the use of JavaScript, but so far I can only make the first element fade away without the second one fad ...

Having trouble with npm i command? Getting an error message like npm ERR! Unexpected token '.'?

I've encountered a sudden issue with my npm install where it stopped working unexpectedly. No matter if I use 'npm i' or 'npm install', I consistently receive an error message stating 'npm ERR! Unexpected token '.'&a ...

The Parallelshell module seems to be inaccessible on npm. What steps can be taken to address this issue

I have made updates to the onchange and parallelshell modules in my package.json file's scripts. "scripts": { "start": "npm run watch:all", "test": "echo \"Error: no test specified\" ...

Is there a way to dynamically import several CSS files in React Native depending on the data stored in this.state?

How can I dynamically import multiple CSS files in a React Native project based on language? import React, { Component } from "react"; if(this.state.language === "he"){ import styles from "./he"; }else{ import styles from "./en"; } I attempted the ab ...

Ways to position a DIV on the right side of the screen using percentage margin to adjust its distance from the edge as the browser is resized

Allow me to provide a clearer explanation here: Imagine an element placed on a webpage with a margin of 10% from the left side. When the size of the page is adjusted, the margin on the left decreases accordingly - for example, 10% from 1400px - 140px, and ...

What is the best method for displaying the toggle button for Drawer/Sidebar above the main content and appbar?

After reviewing Vatsal's suggestion, it appears that moving the toggle button above the drawer is the solution to our main issue. By taking advantage of the open state of the drawer, we can adjust the left property of the button in the toggleButton cl ...

Change the CSS property to override the text-overflow with ellipsis

In my specific scenario, I need to override the default ellipsis behavior that adds '...' to text when using 'text-overflow: ellipsis', and instead use two stars **. Is there a way to achieve this using only Pure CSS? It is important t ...

Support for Node.js and Gulp

Hello, I am a beginner in Gulp and Node Js, and I have encountered the following error but haven't been able to find a solution: [Browserslist] Could not parse /Users/gendyblackman/Sites/blackmanimages/package.json. Ignoring it. Error Message: asse ...