Error in NodeJS (EJS): Unable to locate stylesheet file

Having trouble adding a CSS file to my Node.js project with the EJS Template Engine. The file cannot be found when trying to access it.

GET http://localhost/css/bulma.css net::ERR_ABORTED 404 (Not Found)

Project folder structure

./index.js
./views
    /partials
        /header.ejs
./public
    /css
        /bulma.css

I have included app.use(express.static) as follows

app.use(express.static(__dirname + '/public'));

In my header.ejs file, I include the CSS file like this:

<link href="/css/bulma.css" rel="stylesheet" type="text/css">

Despite trying various solutions, it still doesn't work.

The following approach also does not work:

app.use('public', function(req, res, next){
   console.log(req.url); // Never output
   next();
});

I have also attempted:

app.use('/public', express.static('public'));

Is anyone able to provide insight into what might be causing the issue?

EDIT

Full server code (index.js)

const express = require('express')
const app = express()
const port = 3000

app.use(express.static(__dirname + '/public'));
// set the view engine to ejs
app.set('view engine', 'ejs');

// index page 
app.get('/', function(req, res) {
    res.render('pages/index', {
        template: '../pages/home'
    });
});

app.listen(port, (err) => {
  if (err) {
    return console.log('something bad happened', err)
  }

  console.log(`server is listening on ${port}`)
})

index.ejs for dynamic template system

<header>
    <%- include('../partials/header') -%>
</header>

<%- include(template) -%>

<footer>
    <%- include('../partials/footer') -%>
</footer>

/etc/nginx/sites-available/default

server {
        listen 80 default_server;
        listen [::]:80 default_server;

    root /home/nodejsproject/;

        server_name _;

        location / {
                proxy_pass http://localhost:3000;
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }
}

Additionally,

console.log(__dirname + '/public');

confirms the correct path to the Node.js project directory

SOLUTION: The issue here was with the NGINX configuration.

After consulting the following resource:

I made adjustments to the config file as shown below:

upstream backend {
server localhost:3000;
}

server {
listen 80;
server_name nodeproject;

root /home/nodeproject/;

location / {
try_files $uri @backend;
}

location @backend {
proxy_pass http://backend;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Following is necessary for Websocket support
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}

Answer №1

Instead of just forwarding / without any sub directories/paths, nginx is trying to locate /css/bulma.css within its root /home/nodejsproject/. To resolve this issue, consider implementing the following configuration:

location ~/(.*)$ {
  proxy_set_header X-Real-IP  $remote_addr;
  proxy_set_header X-Forwarded-For $remote_addr;
  proxy_set_header Host $host;
  proxy_pass http://127.0.0.1:3000$1;
}

However, keep in mind that by doing so, your NGINX server will essentially route all traffic to your node.js application, rendering NGINX almost useless.

It is recommended to serve static files directly from NGINX instead.

Answer №2

Hey there, I managed to achieve a similar result by utilizing the class hello and it worked like a charm.

Here's how my project folders are structured:

./index.js
./views
    /partials
        /header.ejs
    /pages
        /index.ejs
        /home.ejs
./public
    /css
        /bulma.css

Styling in bulma.css:

.hello {
  background-color: blue;
}

Content in home.ejs:

<body>
  <h1 class="hello">Hello world!</h1>
</body>

Snippet from index.ejs:

<!DOCTYPE html>
<html lang="en">
  <header>
    <%- include('../partials/header') -%>
  </header>
  <%- include(template) -%>
</html>

Code in header.ejs:

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link href="/css/bulma.css" rel="stylesheet" type="text/css">
  <title>Document</title>
</head>

Snippet from index.js:

const express = require("express");
const app = express();
const port = 3000;

app.use(express.static(__dirname + "/public"));
// set the view engine to ejs
app.set("view engine", "ejs");

// index page
app.get("/", function(req, res) {
  res.render("pages/index", {
    template: "../pages/home"
  });
});

app.listen(port, err => {
  if (err) {
    return console.log("something bad happened", err);
  }

  console.log(`server is listening on ${port}`);
});

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

NPM seems to be neglecting the presence of globally installed packages

I seem to be encountering an issue with locally installing packages while globally installed ones are accessible. It appears that there is an error with the include path, but I am uncertain about the root cause. System : Mac OS X Node : 8.3.1 NPM ...

HTML - various incorrect horizontal alignments

I'm having trouble getting the site logo, site name, and site header to align horizontally on my website. They keep ending up in different places.https://i.stack.imgur.com/5yL5f.jpg I'd like it to look similar to this: https://i.stack.imgur.com/ ...

Trouble with the Width of Selection Box Options

Encountering a peculiar issue with multiple select boxes in my project. Some of the options within the select box are exceeding the width of the box. Proper Dropdown View: https://i.sstatic.net/xDy6I.jpg Incorrect Dropdown Display: https://i.sstatic.ne ...

What could be the reason for the inability to install Angular JS 2?

Setting up Angular 2 for experimentation on my VPS has been quite a challenge. The initial steps can be found here. Upon trying the first command: $ npm install -g tsd@^0.6.0 I encountered success. However, the second step led to an error: tsd install ...

duplicate styling for individual table cells

I am in need of a span element inside a td tag that I am generating within a table. In order to ensure the span fills the td, I have set it as an inline-block with a width and height of 100%. However, when pressing the delete key in the last cell, it star ...

What makes running the 'rimraf dist' command in a build script essential?

Why would the "rimraf dist" command be used in the build script of a package.json file? "scripts": { "build": "rimraf dist ..." }, ...

Stopping a node.js server using the yarn package manager

On my PC, which runs Windows (referred to as "pc"), I have a server running Ubuntu (known as "server"). I installed Visual Studio Code and accessed the server using the vscode extension for remote development. From the vscode terminal on the server, I in ...

Unable to retrieve stored array in mongoose after using the save() function

Currently, I am dealing with a specific type of pattern: board: { id: createdBy: boardlist: [ {id, title: list1, cards: []} {id, title: list2, cards: []} ] I am trying to insert a card into the array of cards for a particular list ID Below is the code sn ...

Can you explain the difference between serif and sans-serif fonts?

Can you explain the distinction between serif and sans-serif when it comes to the CSS font-family attribute? ...

What could be the reason why a specific item is not being retrieved by its ID?

Whenever I navigate to the route: '/gallery', all the items from the file './posts.json' are fetched and displayed on the screen. However, upon navigating to the route: '/gallery/:id', my intention is to retrieve a single item ...

Managing user input in Node.js

Users are required to input a URL in the form (e.g: "") and I need to be able to access and read the content from that URL. I am uncertain about my current method. What should I enter in the URL field below? var options = { url: '....', ...

The height of the parent div increases as its children grow when the browser is resized

I have a set of three divs aligned horizontally within a parent div. As the browser width changes, one of the child divs wraps under the other two when the width is reduced, transitioning them to a vertical alignment. Here are some visual examples: View i ...

The usage of uppercase letters in HTML attributes

I'm struggling to get animation working on my chart. I have been using jQuery's append function to add an animation tag to my HTML page, but for some reason the animation isn't displaying properly. The issue seems to be related to the capita ...

Express bodyParser may encounter difficulties in parsing data sent from Internet Explorer

After creating a server app with Node and Express 4, I utilized jQuery for the front-end. An Ajax call was set up to send data via POST to the server: $.ajax({ cache: false, type: 'POST', url: Config.API_ENDPOINT_REGISTRATION, ...

Tips on adjusting the position of an icon within a dropdown list in HTML?

I have a search field on my webpage with an icon inside it. I managed to find some sample code for the icon. https://i.sstatic.net/WUOot.png However, I am struggling to position the icon to the right of the search box. I've tried adjusting the styli ...

Adjust the navigation text and logo color as you scroll on the page

I am new to HTML and CSS and I am working on a website with PagePiling.js scrolling feature. I want to change the color of my logo image and navigation text dynamically as I scroll to the next section. Specifically, I only want the part of the logo and tex ...

Passing arguments from the command line to an npm script

The scripts section in my package.json is currently set up as follows: "scripts": { "start": "node ./script.js server" } This allows me to use npm start command to initiate the server. All working well so far. However, I ...

Dealing with pagination challenges while working with knex and objection.js

My pagination is functioning correctly without any relations. However, when I introduce images relation, I am losing one post row. This issue seems to be related to the number of images per post - if I only use 1 image per post, everything works fine. I ha ...

Accelerating the npm installation process

Seeking ways to improve the efficiency of npm install during the build process. The package.json contains a list of packages with locked revisions, and I've set up a cache directory using the following command: npm config set cache /var/tmp/npm-cache ...

Styling a component next to another using CSS

Struggling with a simple question here. I'm experimenting with HTML and CSS, trying to create a page with a central content box flanked by two arrow images on each side. While the concept isn't too difficult, I'm running into issues with usi ...