Search code examples
javascriptcssnode.jsexpressejs

CSS File not working on nested routes Express js


I'm building a simple notes app to practice routing with express.

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

  • The "/notes" endpoint renders a page that just lists all the notes created up until that point.
  • The "/notes/add" endpoint is supposed to render a page where you are able to create a new note.

The problem is, I have a css stylesheet in a views directory with some generic styles. I want the styling in this stylesheet to apply to both of the pages rendered by the above mentioned endpoints.

However, it only applies to the "/notes" endpoint. On the "/notes/add" endpoint there is no styling applied, but I get the following error in the browser console (see attached image)...

enter image description here

Note that I already state in the index.js file that all static files should point to the "public" directory first when being referenced.

Any more experienced express users that can help a guy out? Thanks 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;
}

Solution

  • add / in front of your CSS LINK

    • The slash in front of the path means its calling from the root dir
    • change your link to href="/style.css"it should work for more detail