CSS is not being correctly implemented on specific routes in ExpressJS

Every time I access localhost:3000, my CSS functions properly. However, when I try to visit localhost:3000/r/test, the CSS fails to load and I receive the following error message:

Refused to apply style from 'http://localhost:3000/r/styles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

It seems that whenever I have a route with more than one subpath (not entirely sure if that's the right term), my CSS stops working completely. For instance, these routes function correctly:

app.get('/', (req, res) => {
    ...
)
app.get('/cats', (req, res) => {
    ...
)
app.get('/dogs', (req, res) => {
    ...
)

However, the following routes do not work:

app.get('/cats/test', (req, res) => {
    ...
)
app.get('/dogs/blah', (req, res) => {
    ...
)
app.get('/hamster/foo', (req, res) => {
    ...
)

This is what my index.js file looks like:

const express = require('express');
const path = require('path');
const axios = require('axios');
const app = express();

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname + '/views'));

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', (req, res) => {
  res.render('home');
});

app.get('/r/test', (req, res) => {
  res.render('test');
});

app.listen(3000, () => {
  console.log(`Listening at http://localhost:3000`);
});

This is what my test.ejs file looks like:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="styles.css">
  <title>Test</title>
</head>
<body>
  <h1>Hi<h1>
</body>
</html>

Here is the structure of my project:

Project
 |
 +-- public
 |   |
 |   +--styles.css
 |
 +-- views
 |  |  
 |  +-- home.ejs
 |  +-- test.ejs
 |
 +--index.js

Answer №1

To ensure your CSS file is properly linked, place it in the public directory and include a / in the href attribute of the link like this:

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

This will prompt the browser to request the CSS file from localhost:3000/style.css regardless of the current URL.

The use of / signifies the root directory.

Answer №2

For improved performance, consider creating a dedicated route for serving static files.

To update the static path:

app.use('/assets', express.static(path.join(__dirname, 'public')));

Then, in your EJS file, reference it like this:

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

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

Transforming a DIV-styled webpage into a blog-style design using CSS?

Here is my unique HTML page: View My HTML Page (to see the HTML page in action) Code from JSFiddle: :root { background-color: #FFFACD; } div.infoguide { width: 240px; font-family: Arial, sans-serif; font-size: 13px; background-color: #F0FFF ...

What is the best way to merge two arrays into a unified 3d array using JavaScript?

I've managed to get a text-based game up and running, featuring two arrays: the main array (mainArray) that contains information for displaying a bordered map, and a collision array (colArray) that prevents the player from walking off the map. Everyt ...

Strange occurrences observed while looping through an enum in TypeScript

Just now, I came across this issue while attempting to loop through an enum. Imagine you have the following: enum Gender { Male = 1, Female = 2 } If you write: for (let gender in Gender) { console.log(gender) } You will notice that it iter ...

Struggling to connect the Calendar data in AngularJS

I am a beginner in angular js and facing an issue with binding the value of the calendar date from the jquery calendar picker. It seems to be accepting the date only, while all other fields are getting bound correctly. Below is my HTML code: <input id ...

How do I implement data range filtering in Typescript?

Seeking assistance with filtering data by date range and forwarding the results to the client. The objective is to extract tickets created within specific dates, but I keep encountering a console error which is proving challenging to resolve. var befor ...

Adjust hover direction based on container dimensions

My goal is to change the direction of the hover based on the size of the container. If there isn't enough room for the hover effect to appear on the right side, then it should show on the left. For more details, check out this fiddle: http://jsfiddle ...

Updating a nested dependency in Node.js using npm

Currently, I am using express 4.0 with the node module "path-to-regexp". The issue is that path-to-regexp 0.1.7 does not support zero or more path parameters as discussed here. I aim to upgrade path-to-regexp within express to version 1.2.1. While npm u ...

Snatching the lesson found within an iframe

Is it possible to obtain the id from an iframe using the following method? var iFrame = window.top.document.getElementById('window_<?php echo $_product->getId() ?>_content'); However, I am struggling to understand how to retrieve the c ...

"Exploring the Possibilities of iOS Webview with jFontSize

Trying to use jFontSize on a local html page displayed in a WebView, allowing users to change text size. However, adding breaks the script's functionality. Even with another script, the issue persists. HTML: <!DOCTYPE html PUBLIC "-//W3C//DTD ...

What is the best way to remove the excess numbers from the return date provided by the react-date-picker?

I need help displaying only the Month and Day with the format "Tue Oct 22 2019". Currently, I am getting "Tue Oct 22 2019 00:00:00 GMT-0700 (Mountain Standard Time)" when using "react-date-picker". How can I achieve this without having to truncate the te ...

How can custom form validations be implemented with Angular's `useExisting`?

When looking at Angular's documentation on incorporating custom validators into template-driven forms — There is a straightforward example provided for implementing custom validation rules for an input field: required minlength="4" value shoul ...

Can Moment.js be used to calculate the difference in years and months between two dates?

Currently, I am calculating the difference between two dates in months using this code: _result = Math.abs(moment(date1).diff(moment(date2), 'months')) + 1; This code returns an integer representing the duration in number of months. Now, I woul ...

Consistently showcasing images of varying dimensions that are unfamiliar

Currently, I'm in the process of developing a small web application that uses the Spotify API to fetch and showcase top tracks and artists to users. Each track or artist is presented within a Bootstrap panel, with the title displayed in the header an ...

Utilizing shared global variables in node.js environment with elastic beanstalk's autoscaling feature

My node.js app is up and running on elastic beanstalk with auto scaling enabled. Consider the scenario where the following code is in place: var app = express(); var getCounter = 0; app.get('*', function(req, res){ getCounter = getCounter + ...

Setting a specific timeout value for each route in Node Express

As I work on developing my Node v4.2.4 application with Express v4.13.4, I find myself in need of increasing the timeout time for a specific upload route. Based on my research and experience: the default timeout for a Node server is 2 minutes unlike a N ...

Switch between light and dark modes with the MUI theme toggle in the header (AppBar)

I'm currently working on implementing a feature that allows users to switch between dark and light themes in my web app. The challenge I am facing is how to ensure that this theme change functionality is available throughout the entire app, not just i ...

Angular - The argument provided is not compatible with the parameter

I encountered the following TypeScript errors in app.component.ts: Issue: Argument of type '(events: Event[]) => void' is not assignable to parameter of type '(value: Event[]) => void'. Description: Types of parameters 'e ...

Transferring data from PHP to JavaScript using AJAX

I'm currently working on a project that involves generating random numbers on both JavaScript and PHP pages, and I need to display them on the HTML page using JavaScript. So far, I have successfully set up both pages to generate random numbers. Howev ...

Modifying the vertices of geometry to create a low poly terrain is causing unexpected black glitches to appear

I'm currently working on a project that requires creating random low-poly style terrain. To achieve this, I have come up with the following approach: Start by creating a BoxGeometry object to serve as the floor, adjusting the widthSegments and heigh ...