Trouble with CSS loading in Node.js with express.static

Currently, I am working on a web project using Node.js and Express. However, I am encountering an issue with my CSS not loading correctly when serving the static files. Despite trying to use express.static, it doesn't seem to be functioning as expected. Below is a brief overview of my folder layout and code snippets:

const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
const port = 3000;

app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, '..', 'Public')));

app.post('/subscribe', (req, res) => {
  const email = req.body.email;
  
  fs.appendFile('subscribers.txt', email + '\n', (err) => {
    if (err) throw err;
  });

  res.send('Thank you for subscribing!');
});

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '..', 'Public', 'Home', 'Home.html'));
});


app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});
<!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">
    <title>Home</title>
    <link rel="stylesheet" type="text/css" href="Home.css">
    <script src="https://kit.fontawesome.com/3720a64a77.js" crossorigin="anonymous"></script>
</head>
{
  "name": "email-subscription",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.20.2",
    "express": "^4.18.2"
  }
}

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

Being new to coding, any help or advice would be greatly appreciated!

Answer №1

Your Express server is set up to serve the entire Public directory. However, the CSS file Home.css is located within the Public/Home/Home.css subdirectory. To correctly link to your CSS file, you need to use the path Home/Home.css (relative to the directory being served, not relative to the HTML file).

To fix this issue, simply update this line in your HTML:

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

Change it to:

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

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

Determine if all resources on a page in Angular 4 have finished loading by keeping a loader spinning until everything is fully loaded

As part of my work on an Angular app, I am developing a loader to enhance user experience. While the typical approach involves utilizing a boolean parameter for subscribing to HTTP requests, in my case, the service's response consists of multiple ima ...

Deploying Angular 5 to Azure App Services is causing deployment issues

We are facing challenges with deploying an Angular 5.1.3 App to an Azure App Service. Our deployments are triggered by commits to a GitHub repo. Each deployment is taking several minutes and ultimately resulting in the error message below We are seeking a ...

Is there a way to keep the spotlight/shadow position fixed in relation to the horizontal center, regardless of the zoom level?

After working on the following code snippet, I've managed to keep the spotlight centered horizontally, except when the zoom factor is too high. This means that when I zoom in, the spot light no longer remains centered in the horizontal view port. It& ...

What is the best approach for extracting JSON data (using jQuery) from Google Geocoding services?

Obtaining the city name using latitude and longitude is my current challenge. Google Geocoding offers a helpful solution known as "Reverse geocoding". According to the documentation, a GET request needs to be made to the following link: http://maps.googl ...

Could you provide guidance on implementing the delete HTTP request with Axios and try-catch in server.js within the MERN stack?

I'm struggling with my code for removing a resource using Axios in my MERN stack application. Here is the code I'm currently using: app.delete(`/delete/:id`, async (req, res) => { const { _id } = req.params; // use { id } instead of { _id } ...

Query for filtering DateTime values based on UTC timezone using Sequelize

Currently, I am working with Sequelize for MYSql Database. The datetime property in my MySQL database stores values in UTC time zone. However, when retrieving data, I have local time that needs to be compared with the datetime column in the WHERE clause. ...

Combine multiple arrays of JSON objects into a single array while ensuring no duplicates

Trying to combine two JSON arrays into one without duplicates based on date. The jQuery extend() function isn't doing the trick, so looking for an alternative solution that avoids nested $.each statements due to potential large dataset size... [ ...

What strategies can I use to prevent encountering a maximum connections error in MySQL?

It seems like a recurring issue (happening once a week for about 30-40 minutes) where suddenly my database reports max connections when trying to connect via heidisql. Additionally, all api calls return the following error message: Cannot read property &ap ...

Decrease the construction duration within a sprawling Angular 8 project

It takes nearly 10-15 minutes to compile the project in production mode, resulting in a dist folder size of 32MB Here are the production options I am currently using:- "production": { "optimization": true, "outputHashing": "all", ...

What is the reason behind the vanishing of the input field while adjusting the

Why is the input field getting cut off when I resize my browser window, even though I'm using percentages? Here is a screenshot for reference: https://i.sstatic.net/4JrWd.png Shouldn't it resize automatically with percentages? Thank you! Below i ...

Personalized AJAX characteristic inside AngularJs Service

Let's consider a very simple scenario: Here is the code snippet: $.ajax({ type: "GET/POST", url: 'http://somewhere.net/', data: data, beforeSend: '', // custom property }).done().fail(); My main goal is to find a ...

The pagination feature for array field type is malfunctioning on Mongoose, yet it functions properly on the Mongo

I am facing an issue with pagination on the rating field of my product collection. After executing a query in the mongo shell, db.products.find({_id: ObjectId('610bd9233fdc66100f703dd4')}, {ratings: {$slice: [1,1]}}).pretty(); I received the ...

Having trouble retrieving values in NodeJs Express

I'm facing an issue with making a post request as I am unable to retrieve values in Postman; it keeps sending undefined. My Express version is 4.17.1. Here's my code snippet: const express = require('express'); const router = express.Ro ...

Submit a POST request using CoffeeScript to get a string from the returned object

I am encountering a small issue. Whenever I execute myVar = $.post('/check_2/', JSON.stringify({"newname": window.NEWNAME,}), callback, 'json') The variable 'myVar' holds an object. When I use console.log myVar, the output i ...

The reason why React.js does not automatically bind its functions to the "this" object

I cannot understand the purpose of a function not being bound by this object. In my opinion, all functions should be bound by 'this'. So why doesn't Reactjs automatically set bind(this) by default? For instance, in the code below, if I didn& ...

Comparison between referencing the DOM and storing references to the DOM elements

Can you explain the contrast between these two statements? $("#txt").val("123"); versus var txt=$("#txt"); txt.val("123"); Which statement is considered more effective in terms of efficiency? ...

Is it possible to prevent a webpage from being refreshed?

I need help with an HTML page that puts the worker on pause time which will be subtracted from his/her day job. The issue is that when he/she refreshes the page, the timer starts from the beginning automatically. I want it to continue without resetting. Is ...

Using Three.js to showcase 3 different slices of heatmaps within a 3D environment

I'm working on using Three.js to create a 3D representation of a matrix. Each 2D plane in the matrix should be displayed as a 2D heatmap. Here is an example of what I'm aiming for: https://i.sstatic.net/Kj5yb.png My current obstacle is figuring ...

Is there a way to have one element automatically expand when another is selected?

I'm currently utilizing the date and time picker from . However, I need some assistance with the current setup. Currently, the date and time pickers are in separate input fields. In order to select a date, I have to click on the Date input field, and ...

Tips for locating a specific div based on its background color

Take a look at this code featuring a grid - can you figure out how many cells are colored yellow and more? Check it out here ...