Having trouble loading CSS in an express view with a router

I am encountering an issue where I am unable to load my CSS into a view that is being rendered from a Router. The CSS loads perfectly fine for a view rendered from app.js at the root of the project directory.

Below is my current directory structure,

node_modules/
public/
    styles/
        form.css
        home.css
routes/
    form.js
    product.js
views/
    index.ejs
    savoury.ejs
app.js
package.json

This is how my app.js looks like:

import express from 'express';
import path from 'path';
import productRouter from './routes/product.js';
import formRouter from './routes/form.js';
import dotenv from 'dotenv';
dotenv.config();

const port = process.env.PORT || 3030;
const __dirname = path.resolve();
const app = express();
app.use(express.urlencoded({ extended: true })); // access request body for POST
app.use(express.json()); // process JSON in request body
app.use(express.static(path.join(__dirname,'public'))); // Look up our static files
app.set('view engine','ejs');

// Mount our routers
app.use('/product',productRouter);
app.use('/form',formRouter);

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

app.listen(port, () => { console.log(`Server running on port ${port}`) });

The issue seems to arise when I attempt to render a view from a Router named formRouter which is defined in my routes directory as shown below,

import express from 'express';

// Serve our forms from this router
const formRouter = express.Router();

// Render our add savoury form from here
formRouter.get('/add/savoury',(req,res) => {
    res.render('savoury');
});

The view for savoury references the stylesheet in this way:

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

Upon checking the browser console, I see the following error message:

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

I'm unsure of what could be causing this issue. Any assistance or insights would be greatly appreciated.

Answer №1

It appears that an error occurred because the specified MIME type ('text/html') for the stylesheet at 'http://localhost:3030/form/add/styles/form.css' is not supported, and strict MIME checking is enabled.

If you are seeing this error message, it could be because you are attempting to style HTML using a 404 error message.

The reason for receiving a 404 error is likely due to the route or path being called.

Upon closer inspection, the path being requested ('http://localhost:3030/form/add/styles/form.css') does not exist within your file structure:

public/
    styles/
        form.css
        home.css

This indicates that the correct path should be:

https://localhost:3030/styles/form.css

instead of http://localhost:3030/form/add/styles/form.css

To fix this error, adjust your HTML code as follows:

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

By adding a slash in front of 'styles', it signifies that the file is located in the root directory. Omitting it or using './styles' would reference the specific route folder instead.

If this explanation solves your issue, please mark it as resolved.

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

Jquery Triggers Failing to Work Following Ajax Request

I have worked on 2 PHP pages, called "booking.php" and "fetch_book_time.php". Within my booking.php (where the jquery trigger is) <?php include ("conn.php"); include ("functions.php"); ?> $(document).ready(function(){ $(".form-group"). ...

Deselect all event listeners excluding the ones specified in Socket.io

I have a node.js application using socket.io to dynamically load external modules, referred to as "activities," in real-time. Each module binds its own events to the sockets, so when switching from one module to another, I need to remove all event listene ...

Is it necessary for Webpack to process the index.html file for Vue applications?

I am facing an issue with my index.html file where the assets inside the head tag are not loading as images but as the index.html file itself. I have included the following links in my head tag: <link rel="apple-touch-icon" sizes="60x60" href="./assets ...

Running the gulp uncss command with regex to ignore specific elements is not functioning as expected

I have been attempting to integrate uncss into my gulp workflow. In order to exclude certain classes, such as those added through javascript, I am specifying these classes with "ignore" (specifically, I am trying to remove the css from the jquery plugin m ...

developing a custom Bootstrap script specifically tailored for Node projects to be executed using Node.js

Currently, I am in the process of developing a script to streamline the setup of all my projects. My goal is to simplify project creation by simply running 'node bootstrap.js'. The script will then initialize the directory, establish the basic pr ...

Tips for obtaining the XPath for an unordered list and a span element

My goal is to find the xpath that will select the seat "12A" from a webpage containing a list of seats. Here's the source code: <div class="seats" style="top: 48px;"> <ul class="row_12 leftOfAisle"> <li><a class="" data-r ...

After the populate() method, I am unable to modify the Mongoose results

I've encountered an issue with my query while using Mongoose and Lodash: Book .find() .pupulate({ path: 'authors.profile', // find all books and populate the authors.profile field select: 'name' }) .exec() .then( ...

Update operation fails to execute properly with new records being added to the collection

Recently, I wrote an update query that successfully finds a record by its _id and updates it. However, the code works perfectly fine until I add a new record to the collection. When I add a record and query it, the process goes to the success part but retu ...

Stable Banner with Automatic Scroll to Sections

I have implemented a script that allows for smooth scrolling to different sections within a webpage when clicking on links in the top navigation menu. In the HTML, I've assigned IDs to each section (section1, section2, section3, etc.) and linked these ...

Is there an issue with invoking Spring controller methods from JavaScript (via ajax) that is causing them

Using JavaScript to send a request to a method in Spring controller, the code looks like this: <script language="javascript" type="text/javascript"> var xmlHttp function show() { if(typeof XMLHttpReques ...

FlexBox responsive items that are expandable getting cut off

I am currently working on creating a row of expandable items. While I have almost achieved the desired behavior, there are a few issues that I need help with: On Desktop, the items are cut off and not fully visible. On Mobile, half of the items are missin ...

What specific type should be used for validations when incorporating express-validator imperative validations?

Having trouble implementing express-validator's imperative validations in TypeScript because the type for validations cannot be found. // reusable function for multiple routes const validate = validations => { return async (req, res, next) => ...

My program is throwing an error due to invalid JSON format

Snippet of code: var data = $.parseJSON(data); Error message: Encountered Invalid JSON: {times: [{'9:30am','10:00am','10:30am','11:00am','11:30am','12:00pm','12:30pm','1:00pm&apo ...

When utilizing a JQuery .animate function to transition a div from 0px to 450px in height, an unintended margin is produced during the process

I have been attempting to implement a collapsible footer using JQuery. While I have successfully integrated all the animation functions, there seems to be an issue with the animate function affecting the div (id=draw) by creating an unseen margin beneath i ...

The styles in the published npm package are not being applied

Currently in the process of developing a custom npm package named react-clear-carousel, which is essentially a React component with enhanced styles using SCSS. Although I have implemented class names, the styles are not being applied when testing it out. ...

Is the navigation component's loss of properties due to a React router error?

After implementing react router for the first time, I noticed that the props passed to my nav component get lost once a new route is rendered. It's like the items in the cart are disappearing when I click checkout, but reappear correctly when I go bac ...

Exploring the TypeScript compiler API to read and make updates to objects is an interesting

I'm delving into the world of the typescript compiler API and it seems like there's something I am overlooking. I am trying to find a way to update a specific object in a .ts file using the compiler API. Current file - some-constant.ts export co ...

Comparing Angular 5 with --aot and Angular 5 with --aot=false configuration settings

I am having an issue with my Angular application using Angular 5.0.0 and rxjs ^5.5.2. When I run the command ng serve --aot=false, everything works fine. However, when I use ng serve --aot, I encounter the following error: core.js:1350 ERROR Error: Uncaug ...

Navigate to a different page using an AJAX request

Is it possible to use ajax for redirecting to another page? Here's the code I've been working on: <script type="text/javascript"> $(document.body).on('click', '#btnPrintPrev', function() { $.ajax({ url: &apo ...

Cannon.JS ensures that walls are impenetrable

I am currently experimenting with three.js and cannon.js, but I have encountered an issue where I am unable to create solid walls or any stationary objects that can block the player's movement. Below is the code I have been working on so far. I would ...