Node JS server fails to load CSS even with the use of express.static

It's quite absurd, but I've been grappling with a rather nonsensical code conundrum for days now.

I just can't seem to get the CSS and image to load on my Node.js server.

I've tried various solutions (like express.static, etc.), but nothing seems to do the trick.

Could you lend me a hand?

app.js

const express = require('express')
const app = express()
const port = 3000
app.listen(port, () => {
    console.log(`app running on port ${port}`)
})

app.use((req, res, next) => {
    res.sendFile(__dirname + "/index.html");
})

Index.html

<!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">
    <meta name="description" content="Discover my newsletter to learn the basics of digital marketing and growth. Zennit is a Growth agency specialized in scraping and lead generation.">
    <title>Growth Agency - specializing in scraping and leads generation</title>
    <link rel="icon" type="image/png" href="assets/images/favicon.png" />
    <link rel="stylesheet" href="./assets/css/web_version.css">
    <link rel="stylesheet" href="./assets/css/mobile_version.css">
    <link rel="stylesheet" href="./assets/css/tablet_version.css">
</head>

File structure

https://i.sstatic.net/OYk3q.png

Appreciate your assistance :)

Answer №1

To host your files folder as /files, you should use the following code:

app.use("/files", express.static(__dirname + "/files"));

This configuration ensures that any request to /files/* will retrieve static files from the files directory, for example:

<link rel="stylesheet" href="/files/css/style.css" />
<img src="/files/images/some-image.png" />
<script src="/files/js/script.js"></script>

You are currently serving index.html for all requests. To limit it to only GET / or GET /index.html, use the following code:

app.get(["/", "/index.html"], (req, res) => {
  res.sendFile(__dirname + "/index.html");
})

I recommend organizing all static files, including index.html, in a single directory for static hosting. For instance, with this structure:

app/
├─ public/
│  ├─ files/
│  │  ├─ css/
│  │  ├─ js/
│  │  ├─ images/
│  ├─ index.html
├─ app.js
├─ package.json

All you need is:

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

No need for res.sendFile() at all.

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

Determined margin value to replicate the maximum and minimum margin in CSS styling

When attempting to set the margin on an object to 20% with a maximum margin of 200px, I experimented with various methods: margin-left: calc(min(200px, 20%)); and max-margin-left: 200px However, neither property proved to be valid. Is there an alterna ...

Delete the cookie stored in the client browser using Node JS and express-session

Within the realm of app development, I encounter the challenge of restricting user logins across multiple browsers within an existing infrastructure. Our application operates under a single app architecture, meaning users should ideally only interact withi ...

Timeout error occurred in Async.js because the callback was already triggered

Whenever I execute index.js, I encounter an ETIMEDOUT or ECONNRESET error followed by a Callback was already called error. Initially, my assumption was that the issue stemmed from not including a return before calling the onEachLimitItem callback. Consequ ...

Ensure that all Woocommerce products have consistent height while allowing for variations in width

I am struggling with achieving consistent height for all the products on my website, while allowing for variable widths. I attempted to resolve this using UI, but unfortunately it was unsuccessful. Does anyone have suggestions on how to accomplish this u ...

When working with Node.js, it is important to properly export your Oracle database connection to avoid encountering an error like "TypeError: Cannot read property 'execute

Hey there, I am a newbie when it comes to Node.js and Oracle. I've managed to create an app and establish a successful connection to the database. Now, I'm trying to figure out how to utilize the connection object throughout my application. Any s ...

Exploring the distinctions among different material design frameworks

Confirming my grasp of the situation here. Material design is an interface building approach developed by Google. Material lite is Google's public implementation of this concept. serves as an independent open-source adaptation. In addition, Angul ...

Modify the hover color of the FontAwesome span icon

Here's a span that I have: <span class="fa fa-green fa-arrow-circle-o-right" aria-hidden="true"></span> I decided to change the color to #008d4c like this: .fa-green { color: #008d4c; } But when I try to hover over it, the color do ...

Unlocking the potential of the :not selector when combined with the :nth-of-type selector

My current project involves styling a table. I am looking to apply a specific background color to each odd row, excluding the first row which contains headers. I attempted the following code without success: .new-items-table tr:nth-of-type(odd):not(.new- ...

Prevent CSS from resizing text to the very bottom of the page

My goal is to prevent text from overflowing all the way to the bottom of the page, as I need a space for another div at the end. How can I create a gap between the text and the bottom of the page? Additionally, how do I restrict the size and position of t ...

AngularJs - $watch feature is only functional when Chrome Developer Tools are active

My goal is to create a $watch function within a directive that monitors changes in the height and width of an element. This will allow the element to be centered on top of an image using the height and width values. Below is my app.js code: app.directive ...

Searching DynamoDB in node.js using mapped items

In my DynamoDB table, I am trying to retrieve all Items where the Review.ID matches 123. Item: { id: 1, review: { Id: 123, step1: 456, step2: 789, step3: 1234, }, // Add more items here }, Item: { id: 2, review: { Id: 123 ...

Could it be that express-session is not compatible with express 4.13?

I have followed the setup instructions for express-session as outlined in the documentation, but it seems that my cookie is not being created. According to the documentation, simply setting the request.session value should automatically set the cookie. How ...

How can I upload a file with MeteorJS?

(Originally posted on the Meteor forums) Imagine wanting to transfer a file from one computer to a server powered by Meteor through HTTP when the second computer triggers a specific API. I successfully built an application for this purpose using NodeJS, ...

Ensure that the width of the checkbox label in HTML/CSS using Bootstrap remains consistent and fixed, regardless of

Seeking assistance for a bootstrap checkbox button behavior. Currently, the text on the button changes when clicked, but I would like to set a fixed width for the button regardless of the text length and center the text inside it after clicking. Any guidan ...

Dynamic database switching in Node API REST services

Is there a way to dynamically switch the database configuration for my pool in Node/Express application? I am using a REST API with node/express and have multiple databases. What I need is for the API to select the appropriate database based on the user.c ...

Stop redirecting to unsafe websites

I am aware that redirects without validating user input can open the door for attackers to carry out phishing scams, steal user credentials, and execute other malicious actions. For example: res.redirect(req.query.url); But is this type of redirection R ...

Exploring nested documents in mongoDB with mongoose

As a novice full stack web developer, my current project involves creating a movie rating website. To achieve this, I have set up a user schema using mongoose with a ratings subdocument. Here is an example of the schema: const ratingSchema = new mongoose. ...

Ensuring that the app closes completely before launching a new instance with webpack hot module reload

My nest.js application is utilizing webpack hot module reload (hmr), but I am encountering an issue where the reload does not allow the old instance to fully close (including the database connection and telegram bot) before launching a new instance. This c ...

The functionality of 'ngbPopover' in Ng-bootstrap may be affected if the parent container contains a 'transform' css property

Struggling to implement Ng-bootstrap's 'ngbPopover' functionality, I encountered a frustrating issue where the popover would not display after clicking the button. After numerous hours of troubleshooting, I was relieved to discover the root ...

Alert: the task "JSHint" was not located

Currently, I am in the learning phase of programming and have been following along with Steven Foote's guide, "Learning to Program." Chapter 4 is where I find myself currently, having just installed Node, npm, and possibly grunt. The next step requir ...