The mysterious case of the missing CSS file in Node.js

I recently set up a new Node.js Express Project. However, I am facing an issue with the index.ejs file showing the error:

Undefined CSS file ('/stylesheets/style.css').

Here is the content of the index.ejs file:

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
  </body>
</html>

Below is a snippet from the app.js file that I believe is relevant:

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

The directory structure resembles this:

Based on my understanding,

app.use(express.static(path.join(__dirname, 'public')));
should allow me to reference the relative directory
<link rel='stylesheet' href='/stylesheets/style.css' />
, yet I'm still encountering the undefined css error. What could be causing this problem?

UPDATE: Here is my current configuration:

app.js

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('public', __dirname + '/public');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static('public'));

// development only
if ('development' == app.get('env')) { // jshint ignore:line
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);
app.get('/', function(req, res){ res.render('index.ejs'); });

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

index.ejs:

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='stylesheets/style.css' />
  </head>
  <body>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
  </body>
</html>

Answer №1

Give this a shot:

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

or

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

If you need more information, the Express documentation can be found here

Edit 1:

You seem to have an extra '/' in your code.

<link rel='stylesheet' href='stylesheets/style.css' />

Answer №2

It appears that there is a bug related to eclipse specifically causing this issue. The style.css file is being successfully accessed by the page despite an error being displayed on index.ejs.

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

I'm curious about the reason behind the error message stating "Navbar is defined but never used" popping up while working with Vue

After importing the Navbar component from Navbar.vue, I attempted to include it in my app.vue. However, upon doing so, I encountered an error stating 'Navbar' is defined but never used. As a newcomer to Vue, I am unsure of why this issue is occur ...

npm lacks compatibility with the Node.js version 12.18.3

Despite multiple attempts, I haven't been able to find a solution for my issue. On my Windows 10 PC, I have installed Node.js version 12.18.3 and when trying to install a package using npm, I noticed that the npm version returned with npm -v is outda ...

Error: Firebase Cloud Functions reference issue with FCM

Error Encountered An error occurred with the message: ReferenceError: functions is not defined at Object. (C:\Users\CROWDE~1\AppData\Local\Temp\fbfn_9612Si4u8URDRCrr\index.js:5:21) at Module._compile (modul ...

Showcasing distinct signs in a Span within reactJS is simple by utilizing the appropriate syntax

In ReactJS, I am trying to display the following special characters within a span: <span class='child tm'> <img src={tick} class='tick'/>A special character !"#$%&'()*+,-./:;<>=?@[\]^_`|{}~ </span ...

The boundary for the multipart/form-data in the $http post request is missing

I noticed that the boundary I set for the post call appears different in Chrome. How can I make my custom boundary "--test" display correctly on the request payload? var url = '/site/apkUpload'; var deferred = $q.defer(); console.log ...

The Android Webview is experiencing difficulties with loading CSS styles and displaying the blockquote font color effect

I am facing an issue with loading HTML content in CSS through Android WebView. Despite having the code executed, I don't see any observable changes in font color for the text inside blockquote tags Here is the HTML code: <html> <head> ...

Issues arise when implementing a sticky position using CSS with incomplete functionality

I want to create a website with a menu bar that stays at the top even on long pages. However, when I use position: sticky in CSS, the menu disappears after scrolling a certain distance. Does anyone know how to fix this issue? HTML: <nav> <ul cla ...

JQuery UI Autocomplete: Results, Ctrl + A and Delete

I am currently designing a form that allows users to add members to a project. Only members with existing profiles in the system can be added. The form includes an input field for the member's name and a select box for their position, which is initial ...

A step-by-step guide to creating a CSS menu using pure HTML markup

I have been working on the CSS for a menu using some HTML code, but I am stuck and uncertain about my next steps. Here is the CSS I have added so far: #menu-my-integra, ul.sub-menu { list-style: none; padding: 0; margin: 0; } #menu-my-integra li ...

"Run the command 'grunt build' followed by 'grunt

While executing grunt build and grunt serve, a warning message appears: Warning: In order for this task to run, Ruby and Compass must be installed and in your system PATH. Use --force to proceed. Operation aborted due to warnings. grunt version: grunt- ...

An unspecified number of Ajax requests being made within a loop

Here is the dilemma I'm facing, despite trying different recommendations from StackOverflow: Situation: I am utilizing the Gitlab API to display all the "issues" in the bug tracker of a specific project on the system. Challenges: Everything wor ...

Is it possible to create custom Sequelize validators that are based on dynamic values?

Inside my model, there are: level: { type: DataTypes.ENUM('state', 'service-area'), allowNull: false, validate: { isIn: { args: [ ['state', 'service-area'] ], m ...

Is there a way to ensure that the text stays positioned behind the initial image even as the window size is adjusted

<html> <head> <title> Example </title> <style> img:hover {opacity : 0.3;} img {z-index : 1; height : 33%; width : 33%; } .first { position : absolute; top: 0%; left: 0%;} .second {position : absolute; top: 0%; left: 33%; ...

Enable JavaScript in Webdriver Selenium to enhance the functionality of your web

I am facing an issue with my Java program and Selenium WebDriver. The script I have does not detect the button "Open device access" because its style is set to "display: none". Usually, clicking on "Device Access" triggers JavaScript to display the "Open ...

Struggling to Retrieve Specific Keys for Individual Values in Firebase with React Native

I am currently experiencing difficulty obtaining a unique key for each value in the 'users1' table. firebase.database().ref('users1').once('value').then(snapshot => { var items = []; snapshot.forEach((child) => { ...

"Enhance your ASP.NET site with a captivating background

I am currently working with C# in VS2005. My challenge is to add a background image to my login page, which is in the form of an .aspx file. Here is a screenshot of my current setup: Here is the code snippet for my background: <div align="center" ...

Toggle visibility of various items in a to-do list, displaying only one item at a time with the use of JavaScript

I am currently working on a web project using the Laravel framework. I am struggling with implementing a feature where only the title of each to-do item is displayed, and when clicked, it should reveal the corresponding content. However, I have encountered ...

Converting data to a JSON string using jQuery's AJAX method

When I use document.write() for JSON data, it works fine outside of the AJAX call, but not inside the .done() function. I even tried removing the dataType: 'json' parameter, but it still didn't work. $.ajax({ url: "http://api.wundergrou ...

Issue with inheritance from Angular ModalCtrl to ServiceCtrl not functioning as expected

I've been working on linking models to services in order to update global models throughout my app, but it doesn't seem to be functioning as expected. Recently, I delved into AngularJS and I suspect that I may have misunderstood my code. From wh ...

Tips for effectively structuring material-ui Grid in rows

I am currently using the material-ui framework to create a form. Utilizing the Grid system, I want to achieve the following layout: <Grid container> <Grid item xs={4} /> <Grid item xs={4} /> <Grid item xs={4} /> </Gr ...