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

Can you identify the specific name of the IE CSS bug affecting double vertical padding?

(Just when I thought I've encountered all the strange IE CSS bugs, here comes another one. Is there a name for this double-vertical-padding bug?) After creating a simple test case that worked perfectly in browsers like FF and Opera, I was surprised t ...

Is there a sweet syntax for CSS variables available?

What about using this instead: :root { --primary-color: gray; --secondary-color: lightgray; } var(--pc) Is there a more concise syntax available, perhaps shorter than var(--pc)? ...

Can you explain the guidelines for overlapping CSS media queries?

When it comes to spacing out media queries accurately to prevent overlap, how should we approach it? Let's examine the following code as an example: @media (max-width: 20em) { /* styles for narrow viewport */ } @media (min-width: 20em) and (max ...

When there is an error or no matching HTTP method, Next.js API routes will provide a default response

Currently, I am diving into the world of API Routes in Next.js where each path is structured like this: import { NextApiRequest, NextApiResponse } from "next"; export default async (req: NextApiRequest, res: NextApiResponse) => { const { qu ...

Running programs in various languages

Working on my project using raspberry pi. I have developed programs in both python and node.js. I am looking for a way to execute these programs based on specific conditions, all with just a single click of an executable file. Can anyone provide guidance ...

Tips for integrating CSS keyframes in MUI v5 (using emotion)

Hey there! I'm currently working on adding some spinning text, similar to a carousel, using keyframes in my React app. The setup involves MUI v5 with @emotion. Basically, I want a "box" element to show different words every few seconds with a rotating ...

Make sure to log in before running a post request during unit testing with Chai and Mocha

Currently, I am working on testing my post function to only accept data from users with specific permissions. I have successfully implemented a separate login function that is functioning correctly. However, my test code is not recognizing the logged-in us ...

The Ineffectiveness of Social Media Sharing in WordPress

I'm encountering an issue with adding social media sharing buttons to my website's product page. Although I've implemented the PHP code, clicking on the Facebook button only redirects to a page displaying a share button and URL, but it doesn ...

Adonis session is failing to persist between test runs

Recently, I developed a basic eCommerce application using Adonis JS. One feature of the application is the cart functionality, which should increase the quantity if the user tries to add an item that is already in the cart. To test this feature, I made u ...

The POST request functions flawlessly on the local server, but encounters issues once deployed to Google Cloud Platform

Even though the Axios post request works fine on my local server, it throws a 404 not found error after I deploy the project on Google Cloud. On localhost, all requests are directed to URLs starting with http://localhost:9000/api/..., handling post reques ...

What is the best way to retrieve routes from a custom REST API using React Native?

Working on developing an app for my company has been an exciting challenge for me. Being new to programming, I decided to take a react-native course and a nodeJs course to enhance my skills. One particular question I have is related to fetching data from m ...

What is the best way to transfer axios requests from my routes files to the main app.js in node js?

I'm trying to export my routes from a folder to my app.js file using axios instead of express.Router(). However, I'm having trouble figuring out how to do this. In my project, I have a USER.JS file inside the routes folder: const express = requ ...

Creating responsive modal windows in Vue and Laravel to dynamically adjust to the screen size

I am currently working with a modal window code snippet. <transition name="modal" @close="showModal = false"> <div class="modal-mask" style=" width: 90% !important;"> <div class="modal-wrapper"> < ...

Error message: The 'run-android' command is not recognized after installing a new package in a React Native project

Progress on my React Native project was smooth until I attempted to add new packages. After running the project on an android emulator, I encountered an error stating Command run-android unrecognized. Make sure that you have run npm install and that you ar ...

Node.js vulnerability labeled as CVE-2021-38628

Description: Enhance security measures by disabling the use of TLSv1.0 protocol and transitioning to a more secure option like TLSv1.2. To perform a manual test, utilize the following openssl commands: openssl s_client -connect ip:port -tls1. If succes ...

AWS Lambda serverless deployment of Angular Universal is failing to detect javascript files in the dist/browser directory

After following the steps in this tutorial for deploying to a lambda function, I encountered some issues. When testing it using serverless offline, I kept getting 404 errors for each compiled JS file. However, once I deployed it, the errors changed to 403. ...

The beforeCreate function is failing to execute when a new user is being created

I'm currently working with sailsjs version 0.11.0. My goal is to ensure that when a new user is created, their password is encrypted before being stored in the database. To achieve this, I have implemented the use of the bcrypt library. In my User.js ...

What is causing the malfunction of the position within this particular section?

On my website, I have a specific section where I want to showcase four products with arrows on both sides for navigation. However, I am facing an issue with the positioning of the elements. Can someone take a look and help me figure it out? Check out this ...

Arranging Elements Using CSS

Currently, I am working on aligning and positioning my items using CSS. However, I'm a bit confused about the right approach. Here is a demo of my current progress: Demo Link I aim to achieve a layout similar to this sketch: Sketch Image Apologies ...

Leveraging the power of Express and everyauth for implementing conditional authentication with Google OAuth2

Trying to integrate everyauth with Google OAuth2 has been a bit challenging for me. I specifically need authentication to be successful only if the user belongs to my company's Google Apps domain. However, I am struggling to find a way to gracefully s ...