Difficulty with routing stylesheets in my Node Express server

Currently, I am setting up the back-end structure for my website. The file setup looks like this:

public
  css
    main.css
    main_b.css
  index.hbs
  index_b.hbs
server
  server.js

To reference style sheets in the index files, I use link attributes with:

rel="stylesheet" type="text/css" href="main.css"

rel="stylesheet" type="text/css" href="main_b.css"

My server.js script is as follows:

const path = require('path');
const fs = require('fs');

const express = require('express');

const app = express();

const hbs = require('hbs');
    
hbs.registerPartials(path.join(__dirname, '../public/partials'));
app.set('view engine', 'hbs');

app.use(express.static(path.join(__dirname, '../public/css')));
    
// activity logger 
app.use((req, res, next) => {
  const now = new Date().toString();
  const logEntry = `${now}: ${req.headers.host} ${req.method}${req.url}`;
  fs.appendFile(path.join(__dirname, '../server/server.log'), logEntry.concat('\n'), (error) => {
    if (error) {
      console.log(error);
    }
  });
  process.env.route = req.path;
  next();
});

app.get('*', (req, res) => {
  switch (process.env.route) {
    case '/': // home page
      res.render('../public/index.hbs');
      break;
    case '/b': // basic layout 
      res.render('../public/index_b.hbs');
      break;
    
    default: // unknown routes
      res.render('../public/index.hbs');
  }
});

app.listen(3000);

When requesting localhost:3000, the log entry is accurate:

Thu Jan 24 2019 07:57:08 GMT+0200 (Eastern European Standard Time): localhost:3000 GET/

Similarly, when accessing localhost:3000/abc, the log reflects the request:

Thu Jan 24 2019 07:57:08 GMT+0200 (Eastern European Standard Time): localhost:3000 GET/abc

However, issues arise when testing sub-routes like localhost:3000/abc/def. The CSS doesn't render correctly and the log shows:

Thu Jan 24 2019 08:04:55 GMT+0200 (Eastern European Standard Time): localhost:3000 GET/abc/def Thu Jan 24 2019 08:04:56 GMT+0200 (Eastern European Standard Time): localhost:3000 GET/abc/teamk-reset.css Thu Jan 24 2019 08:04:56 GMT+0200 (Eastern European Standard Time): localhost:3000 GET/abc/main.css

I've attempted to adjust the CSS lookup path using the index and redirect properties of the options object in Express.static(), but have not succeeded.

Any guidance or references on resolving this issue would be greatly appreciated. Otherwise, I may need to reconsider my approach to route querying.

Answer №1

After some investigation, I was able to identify and resolve the issue in my code.

In order to properly reference styling sheets in index files, they should be linked using the following attributes:

rel="stylesheet" type="text/css" href="/main.css"

rel="stylesheet" type="text/css" href="/main_b.css"

The names of the stylesheets must be preceded by '/' to ensure correct URL construction.

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

Encountering difficulties when trying to import a function from another file in node.js using ECMA standards

I am having trouble exporting these 2 functions from callModule.mjs in my app.js. Every time I try to do this, I encounter the following error: import {showUsers, callUserProfile} from "./callModule.mjs" ^ SyntaxError: Unexpected token { ...

What is the best way to implement this header style with code?

I came across this design from a potential client recently, even though we didn't end up working together. I thought it would be a good exercise to try coding the design for practice purposes. Just to clarify, this is not my original design and I have ...

I encountered an issue while trying to generate a React app with npx

Struggling with setting up a React app on my Windows machine, looking for some assistance here. I've tried running the following command in Hyper Terminal: npx create-react-app new-app After checking that my Node.js version is 12.16.1 and both npm and ...

Creating a List with Sublists that are displayed when hovering over the parent List is a key element of effective design

Hovering over 'View Rows' should open up both New Records and Old Records <div> <li>Add Rows</li> <li>DeleteRows</li> <li>View Rows <ul> <li>View New Records</li ...

Ensure Focus Retention Upon Clicking Inside Iframe with li a:focus

How can I prevent my ul.SideNav_Main li a:focus class from losing focus when I click on the iframe or elsewhere on the page? Shouldn't it maintain focus until I click on another URL in the list? Is it possible to solve this issue with just CSS, or wo ...

Disabling sessions in KrakenJS

I am currently developing an application using KrakenJS 1.0 and my main goal is to completely deactivate sessions. If you're wondering why I want to do this: I simply have no use for session handling in this particular project. I want to eliminate an ...

Implementing subscriber addition on Mailchimp 3.0 using Node.js and HTTPS

Here's the content of my app.js file: const express = require("express"); const bodyParser = require("body-parser"); const request = require("request"); const https = require("https"); const app = express(); app.use(express.static("public")); app.u ...

Keep the footer at the bottom of the screen without needing to define a 100vh in Material UI

In the process of developing my react app with MUI framework, I encountered various challenges in creating a sticky footer at the bottom of my screen. After exploring different solutions, one approach that I found most satisfactory is as follows: export de ...

Using Docker to create a scalable application with Node.js and MongoDB

When trying to dockerize my Node.js application, I encountered an error while running the command `docker-compose up`. The error message was: app | /bin/sh: 1: [: “npm”,: unexpected operator. Dockerfile FROM node:latest RUN mkdir -p /usr/src/app WOR ...

Tips for positioning your side navigation menu parallel to the page edge

Im looking to have the side navigation floated to the left as I scroll down the page. I tried using the sticky property, but it didn't work out. Here's a snippet of the code: .sticky-class { position: sticky; top: 30px; } This is how my HTML ...

Can I include specific errors in req.validationErrors()?

While I'm utilizing express validation for data input validation which works well for most cases, there are certain scenarios where traditional validation methods are not applicable (such as checking the validity of a Facebook token) Is there a way t ...

The Azure web app does not send a Set-Cookie header

My setup involves a frontend communicating with a backend. During the login process, the backend generates a cookie and sends it back to the client. For logout, I want the backend to erase the cookie. I haven't specified any attributes below. https: ...

Submitting form data via Ajax to be processed by Express.js with body parser

Having trouble sending form data to Node.js via AJAX. Using Express with body parser on Node.js However, receiving undefined in req.body. After searching extensively online and trying various solutions without success, I am seeking assistance on the c ...

The reason the section's height is set to 0 is due to the absolute positioning of the div

Currently, I have a section tag with three divs inside that are positioned absolute (used for the isotope plugin). <section id="section1" class="cd-section"> // pos. static/relative has height 0px <div class="itemIso"> // pos. absolute, he ...

Discover if every single image contains a specific class

HTML : <div class="regform"><input id="username" type="text" name="username" placeholder="Username" required><h3 class="check"><img src=''/></h3></div> <div class="regform"><input id="password" type=" ...

Having issues with NodeJs and creating a MongoDb database? Looking for a solution?

Take a look at this snippet of code written for NodeJS 8.10 inside a lambda function using the mongodb drive. You can find it in the context of this helpful tutorial. The purpose of this code is to create a database called testlambda2 and return the value ...

What could be the reason for NPM failing to work following an update?

Just two days ago, I updated NPM and now it's suddenly not working on my Windows 10 20H2 platform. Every action I take results in the same error message: C:\Users\ethan>npm internal/modules/cjs/loader.js:883 throw err; ^ Error: Canno ...

"Enhance your networking capabilities with a Node.js HTTP proxy featuring a dynamic proxy

I'm attempting to make websockets function properly with node-http-proxy. The unique aspect is that I am using a proxy table configuration: var options = { router: { 'a.websterten.com': '127.0.0.1:150', 'b.websterten. ...

Adjusting the Height of the Video Jumbotron in Bootstrap

One of my main goals is to create a jumbotron with a video that plays, occupying 100% width and 70% height of the screen. However, I am facing an issue where the video follows the scrolling behavior when I don't want it to. Specifically, as I scroll d ...

Adjusting the width of the header in Wordpress themes like Genesis and Foodie Pro

Struggling with the header appearance on my website. I want the blue section to be full width while keeping the logo and navigation the same width as the content area (1040px). I'm new to Wordpress and unsure how to make this adjustment. Someone sugg ...