Problem with Express server not fetching or applying public stylesheet

As I delve into the world of serving pages with node, express, and ejs, I encountered an issue with linking a stylesheet to my index.ejs file using a public folder. Despite setting up the link correctly in the HTML code, the styles were not loading when I viewed the page in my browser. Strangely, there was no request for the stylesheet showing up in the network tab either. However, when I directly visited localhost:3000/styles.css, the file displayed without any problems. Here's how my files are structured:

index.ejs

<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sam's Site | <%= title %></title>
    <link rel="stylesheet" src="/styles.css" type="text/css">
  </head>

  <body>
  ...
  </body>
</html>

app.js

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

app.set('view engine', 'ejs');

app.listen(3000);

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

app.get('/', (req, res) => {
  res.render('index', {title: 'Home');
});

My app.js is located in the top level folder, index.ejs in a views folder, and styles.css in a public folder. Everything seems configured correctly, as the header appears normally and the link tag is correctly set up to load the stylesheet. Even after trying different path variations for the source of styles.css and ensuring that my CSS syntax is valid, the stylesheet still fails to load. Can someone shed light on why this might be happening?

Answer №1

Consider using :

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

Rather than:

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

By default, Express uses the public folder so there is no need to specify the path.

Answer №2

Make sure to use the href attribute in your link tag, not the src attribute.

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

Angular experiencing a callback mismatch error while using Auth0

Greetings! I am currently utilizing Auth0 with Nodejs and angularjs in my project. Here are the goals I aim to achieve: 1. User signup using Auth0's lock feature 2. When a user logs in, a callback should be triggered on my Node.js server 3. Ret ...

What is the process by which headers are received in a pre-flight request without a response being generated?

Recently, I've delved into the world of CORS and pre-flight requests. From my understanding, it's essentially an initial OPTIONS request sent before the actual request is made. If the server approves, the real request follows. But what puzzles me ...

Ubuntu installation of the Gekko Auto Trading bot encountered a technical error

I am fairly new to coding in Ubuntu and attempting to set up the Gekko auto trading bot on a web server that I created. Following instructions from a website, I have completed all the steps. However, when I try to start the service using: node gekko --ui ...

Issue encountered during the parsing of an expression by MySQLx in a Node.js application

I recently downloaded the @mysql/xDevApi library from the NPM repository at here and it is currently version 1.0.5 Encountering errors when attempting two different methods:- collection.find("$.name == :name") .bind('name','Test') ...

Is there a way to extract the "title" from this particular array?

code /// https.get(`https://discordemoji.com/api?request=search&q=coffee}`, (resp) => { let data = ''; resp.on('data', (chunk) => { data += chunk; }); resp.on('end', () => { console.log(data) const embe ...

Ways to Delete Multiple Documents in MongoDB

I'm facing a challenge while attempting to delete a feature. I need to ensure that all related comments are also deleted along with the feature, but I'm unsure of how to achieve this. This is my deleteFeature function - exports.deleteFeature = ( ...

Creating stylistic layouts for text using CSS

After spending the last hour designing a web page, I am stuck on a particular issue that I just can't seem to solve. I need to write several paragraphs while adhering to two specific constraints: 1) The div in which the text resides must be centered ...

What is the best way to use jQuery to adjust the size of a slider image based on a percentage of the browser window

I've been searching all over for a solution to this issue, but so far I haven't had any luck. Basically, I have an image that is 1800 pixels wide by 500 pixels high. I need this image to adapt to all screen resolutions. Instead of having a fixed ...

Interact with an external JavaScript function using a button within a web application

I have a JavaScript file called dmreboot_service.js in my /js folder. By running this file with the command node /js/dmreboot_service.js, it successfully triggers a direct method in Azure. My goal is to be able to run this function or file when a button o ...

Verify that the text entered in the form is accurate, and if it meets the required criteria, proceed to the next

Is it possible to achieve this without using JavaScript? If not, I'd like to find the simplest solution. I have a form that functions similar to a password entry field, and I would like to redirect users to a certain page if they type in a specific p ...

Basic color scheme

I'm attempting to change the background color behind a partially transparent .png div. The CSS class that modifies the div is ".alert". Manually editing the .alert class background color works perfectly, and now I want to automate this on a 1-second c ...

The writeToDB function is triggered only one time

I've encountered an issue with my node.js code where the writeToDB function is being called, but data is not inserted in the database after the first time. Can someone help me understand why? uploadInfoObject = { ProcessId: pid, Type: "type", ...

When attempting to open the HTML file through an Express application, the background image specified by `background-image: url()` may

Upon opening the html file by directly clicking on it, the background-image styled with url() functions correctly. However, when I open this file within an express app using res.sendFile(), the background-image fails to display. Interestingly, all other CS ...

Using Webpack 4 to import SCSS files with aliases

Currently, I am running a node script that is using webpack to bundle multiple folders for various installations on our server. MiniCssExtractPlugin.loader, { loader: 'css-loader', options: { ...

Carousel Image Alignment Issue on iPhone SE Portrait Mode: All Images Centered Except One

Check out this website: It functions perfectly on Desktop browsers at all scales and works on Mobile devices in Landscape mode. However, I noticed that when using Portrait mode on my iPhone SE, the first image in the carousel appears off center in Chrome ...

Tips on how to prevent certain classes from being impacted by a hue-rotate filter applied to all elements on a webpage

I am currently in the process of adding a feature that allows users to choose between a dark or light theme, as well as select a specific theme color for the app. The implementation involves using CSS filters such as invert(1) for the dark theme and hue-ro ...

The ineffectiveness of setting width to 0

When I set @media screen and (max-width: 700px), aside {width: 0}, it doesn't disappear. Even after resizing the window, it remains as null space with width: 52px. What could be causing this issue and how can I resolve it? * { margin:0; padding ...

How to Customize the Placeholder Text of a TextField

When working with the TextField API, I noticed that there is no mention of how to style the pseudo placeholder element of the input element. I want to customize the default styling of the placeholder text, but the usual CSS tricks don't seem to work ...

Guide on uploading personal projects on Sinopia (npm adduser not working for private repository)

After setting up a private npm registry using Sinopia, I am facing an issue - I cannot publish anything to it. In short: Sinopia does not support the npm adduser command, but has its own user management system. Npm requires a valid user created before u ...

Tips on how to achieve a 50% width within a bootstrap input group

Need help setting the width of a select tag <div class="input-group"> <select class="form-select" style="width: 50%;"> <option selected value="dummy">Dummy</option> <opt ...