Troubleshooting: CSS file not functional within nested routes of ExpressJS

I'm currently working on a notes app to enhance my skills in routing using express.

There are two endpoints: "/notes" and "/notes/add".

  • The "/notes" endpoint displays a page with a list of all the notes created so far.
  • The "/notes/add" endpoint should display a page where users can create a new note.

The issue I'm facing is related to styling. I have a css stylesheet in a views directory that contains some basic styles. My goal is for these styles to apply to both pages generated by the above endpoints.

However, the styling only works on the "/notes" endpoint. For the "/notes/add" endpoint, the styling is not applied, and I'm encountering an error in the browser console (refer to the attached image)...

https://i.sstatic.net/r6E7v.png

Note that in my index.js file, I have already specified that all static files should first reference the "public" directory.

If there are any experienced Express users who can provide assistance, I would greatly appreciate it. Thank you in advance.

/index.js:

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

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static('public'));

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

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

app.listen(3000, () => {
    console.log("LISTENING ON PORT 3000!");
})

/views/notes.ejs:

<!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="style.css"/>
    <title>Document</title>
</head>
<body>
    <main>
        <h1>All Notes</h1>
        <ul>
            <li class="list">Wish List</li>
            <li class="list">Homework for Friday</li>
            <li class="list">Workout Plan</li>
            <li class="list">Cooking Recipe</li>
            <li class="list">Monthly Budget Plan</li>
        </ul>
        <a href="/notes/add">Add +</a>
    </main>
</body>
</html>

/views/add.ejs:

<!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="style.css" type="text/css"/>
    <title>Document</title>
</head>
<body>
    <main>
        <form action="" method="post">
            <textarea></textarea>
        </form>
    </main>
</body>
</html>

/public/style.css:

main {
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: red;
}

.list {
    font-size: 1.3rem;
}

Answer №1

Don't forget to include a / at the beginning of your CSS LINK

  • Adding the slash at the start of the path indicates that it is being called from the root directory
  • Update your link to href="/style.css", and it should now function correctly for more information, check out this link

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

Determine the card type based on the card number

My array of card types is structured like this: var cards = new Array(); cards [0] = {name: "VISA", length: "13,16", prefixes: "4", checkdigit: true}; cards [1] = {name: "VISA_DELTA/ELECTRON", length: "16", prefixes: "417500,4917,4913", checkdigit: tr ...

What was the reason for needing to employ `toObject()` in mongoose to determine if an object contains a certain property?

From what I understand, there is no .toObect() function in JavaScript, but it is used in mongoose to convert mongoose documents into objects so that JavaScript built-in functions can be used. I sometimes struggle with when to use it. There are instances w ...

What role does the index number play in MongoDB/Mongoose and why is it important?

When using mongoose with Mongo DB, this is how I set up indexes: UserSchema.index({ email: 1, username: 1 }, {unique: true}); Initially, I only had the email field indexed. However, since usernames must also be unique and I need to check if a username ...

Is the key to achieving optimal client interactions within a client layout, while still maintaining its role as a server component, truly possible?

My current challenge involves managing modals opening and closing with server components instead of client components. In the past, I used to lift the state up to my Layout for client components: export default function Layout({ children }) { const [showP ...

Utilizing Angular 9's inherent Ng directives to validate input components within child elements

In my current setup, I have a text control input component that serves as the input field for my form. This component is reused for various types of input data such as Name, Email, Password, etc. The component has been configured to accept properties like ...

Tips for displaying website preloader just once

I recently added a preloader to my website, but I'm having trouble getting it to only play once per visit. Ideally, I want the animation to show up when the site is opened in a new tab or browser window, but not when navigating through the domain by c ...

adjust the value of an attribute in a dynamic stylesheet using jquery

I'm trying to create a dynamic stylesheet using a combination of jquery, css, php, and html. My approach involves making an ajax request (using jquery) to pass the width of my screen to a php css file. However, I am facing an issue where the php css f ...

Image floating to the left and right sides within a group, with the text vertically aligned in the middle of a div of unspecified height

Can text be vertically aligned in the middle of a div with an unknown height when there is a floated image present? Specifically, for the first and third div group of 'groupsection2', the image will float to the left; and for the second and fourt ...

I am looking to update all npm packages within my node-loopback application

I have a node application that currently has all node packages compatible with node version 0.10.25. However, I now need to upgrade all the packages to be compatible with the current node version which is 10.15.3. I've attempted two methods so far: ...

Cypress - simulate multiple responses for watchPosition stub

I have a small VueJs app where clicking on a button triggers the watchPosition function from the Geolocation API to retrieve the user's position and perform some calculations with it. Now, I want to test this functionality using Cypress testing. To ...

I'm trying to use Javascript to dynamically remove rows, but my code seems to be causing some issues

When a user enters text into a form, it is stored in a variable called 'userInput'. I have an HTML table with the ID "myTable". My goal is to use JavaScript to iterate through the table and remove all rows where the value of the 3rd column does n ...

Utilizing custom template tags with script tags for componentization within Django applications

Currently working on a Django project with multiple apps. One of the main apps serves as the base, housing global elements like CSS, JS, and custom template tags (referred to as CTTs). I'm interested in creating CTTs that contain HTML and script tags ...

`How can I troubleshoot path obstacles when transferring files in node.js?`

I am having trouble moving a file from an HTML form to another folder using a cloud function. I am new to both node.js and firebase, so I am unsure of what I am doing wrong. This is my current code snippet: const fileMiddleware = require('express-mult ...

Transfer information(text) to the clipboard using Vue (Nuxt js)

When the vs-button is clicked, I want the value of single_download_link.pdfId to be copied to the clipboard. I attempted it like this, but it did not work. I do not want to use the v-clipboard node module. Can someone please assist me with this? Thank you. ...

Updating a useState hook in react with a specific condition: a step-by-step guide

Utilizing react hooks (useEffect and useState) in conjunction with firebase has been a seamless process for me. Having a collection of users that can be easily retrieved from firebase, the basic structure of my code appears as follows: const [users, setUs ...

Adapting the current codebase to be compatible with Typescript

Currently, my codebase is built with redux, redux-saga, and react using plain Javascript. We are now considering incorporating Typescript into the project. Some questions arise: Can plain Javascript files coexist with tsx code? I believe it's possibl ...

Tips for utilizing the express-uploadfiles package

I am encountering an issue when trying to print the name of a file to the console. When I provide the server path along with the file, I receive the following error message: TypeError: Cannot read properties of undefined (reading 'file') This i ...

Best practices for incorporating and leveraging node packages with Laravel Mix

As I embark on my Laravel (v 8.x) Mix project, I am encountering challenges when it comes to incorporating JavaScript from node modules. To kick things off, here is a snippet from my webpack.mix.js: mix.js('node_modules/mxgraph/javascript/mxClient.mi ...

Exploring ways to pass props in functional components in React Native

I am currently exploring how to create an API in React Native with TypeScript without using the class extends component. However, I am struggling to figure out how to access and send props from one const view to another function: App.tsx import React, {us ...

Hover over this area to reveal the hidden text as it slides into view

My goal is to hover over truncated text and reveal the full length of the dynamic text. However, I am struggling with removing extra space at the end of shorter text when hovered and displaying all the text for longer ones. I have a solution that almost w ...