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:

https://i.sstatic.net/6QB77.jpg

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.

https://i.sstatic.net/vkx6s.jpg

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

Tips for checking form input validity prior to opening a modelDialog

After successfully validating all required form fields, I am trying to open a modal dialog. Although I have managed to validate the form, I am struggling to write the code that will trigger the opening of the modal dialog upon successful validation. Do y ...

What advantages does Snap.svg offer compared to the HTML5 native SVG DOM API?

Can the differences between Snap.svg and HTML5 native SVG DOM API be compared to jQuery vs HTML5 native DOM? Apart from potential cross-browser disparities, assuming modern browsers support SVG well, what advantages does Snap.svg offer? What are the pros ...

What are alternative ways to add an HTML snippet to an existing file without relying on jQuery?

Is it possible to inject the entire content of an HTML file, including all tags, into a specific div using only JavaScript? Alternatively, would it be necessary to append each element individually and create a function for this purpose? ...

The function setCustomValidity() will continue to display even after the form has been successfully filled out

My form is very simple and I am trying to validate it using the required attribute: <form name="form"> <label for="Header">Title</label> <input type="text" class="span5" name="Header" ng-model="Message.header" placeholder="Title" on ...

Implementing AJAX to dynamically update information based on user's selection from a dropdown

I need to dynamically adjust the opacity of my graph bars without requiring the user to manually refresh the page. I'm considering using AJAX for this purpose. How can I implement this functionality? const opacitySlider = document.getEle ...

The face textures are not being applied correctly to the model imported in THREE.js

I'm having trouble importing a model exported from blender using the THREEJS exporter. The model loads correctly in my scene with the materials applied, such as the car appearing yellow and the glass being transparent as intended. However, I am facin ...

An unusual icon with three varying sizes in a single file

I have come across an interesting favicon file. Click here to download the favicon file Unfortunately, I am unable to upload this image file as it does not meet the required format standards. Upon viewing the file in Windows 7, a fascinating discovery w ...

Android TV with Ionic

I am working on an APK for Ionic on Android TV and I am facing an issue with the arrow controls. The APK runs on the device but the behavior is not correct. When using arrows to shift the app, the focus does not work as expected. It skips some divs. Here ...

Encounter Issue: "Describe" function not recognized. This error occurred during the activation of Mocha Test

https://i.sstatic.net/WBSm6.png Upon my installation of mocha, I encountered an issue while running a test using a command, resulting in the error message "describe is not a function." ...

Stylish Titles with Bootstrap

I have been trying to eliminate the border that is creating the panels Body, but I am encountering some difficulties in locating it. Here is the code snippet for my panel: <div class="panel"> <div class="panel-heading"> <span class ...

Using async/await in React.js to handle API calls results in a

It's puzzling to me why calling the API directly using async await in useEffect() results in getting data immediately when the component mounts, but when I call getLevels() from selectApi.js, it returns undefined. Take a look at the code snippet below ...

What is the best way to dynamically link an Angular Material table with information pulled from the backend server

I am attempting to connect a mat-table with data from the backend API following this Angular Material Table Dynamic Columns without model. Below is the relevant content from the .ts file: technologyList = []; listTechnology = function () { ...

Clicking on hyperlink within email to open in default web browser

I am facing a problem with my Angular web app. Here is the scenario of the issue: When I send a link to my app via email and try to open it from a mobile email client using a short version of a browser or webview (not sure what it's called), I encou ...

Unleashing the power of eventListeners through exponential re-rendering upon state updates

Trying to implement an eventListener for "keydown" to update the state (a boolean named showMenu). I placed it inside a useEffect, but it's not functioning correctly and I can't pinpoint the issue. When I include showMenu in the dependency arra ...

Widget remains static until job triggers data refresh, preventing CSS transition initialization

I am struggling with the html/coffee/scss aspects, although I'm comfortable with Ruby. On my website, I have implemented a hotlist widget sourced from this link: https://gist.github.com/andre-morassut/8705385. While it functions properly, I encounter ...

The display of Bootstrap Cards may become distorted when incorporating J Query

I am attempting to design a dynamic HTML page that pulls data from a JSON response using an AJAX request. My goal is to display three columns in a row, but currently I am only seeing one column per row. I would greatly appreciate any guidance on what migh ...

Executing Angular CLI tasks using a script file rather than directly from the CLI? Embracing the power of Localization and Internationalization

Our Angular 2 app is gearing up for internationalization/localization, and I am looking to create scripts that can handle tasks such as generating translation source files or building/serving the application with translations in a specific language. Inste ...

Is there a way to prevent a tag from being clickable on the entire row, except for the actual link itself?

My question is why, when using the a tag, the entire row on the right becomes clickable as well? Despite there being no link, the area at the back of the row on the right side is clickable. Is there any way to remove this clickable area? <a id="ba ...

Utilize npm libraries within the main directory of Sage 8.5.3 theme

When attempting to add npm libraries in the root of Sage 8.5.3, I encountered an error in the console stating that 'require' was not found. var GoogleMapsLoader = require('google-maps'); GoogleMapsLoader.load(function(goo ...

How can we translate this php json_encode function into Node.js?

Seeking the equivalent Node.js code for this PHP Script: $SMA_APICall = "https://www.alphavantage.co/query?function=SMA&symbol=".$symbolValue."&interval=15min&time_period=10&series_type=close&apikey=R3MGTYHWHQ2LXMRS"; $SMAres ...