"Trouble with Express.js: CSS isn't loading, yet HTML displays

Click here to view folders and files server.js is the code I have created so far

//importing packages
const express = require('express');
const admin = require('firebase-admin');
const bcrypt = require('bcrypt');
const path = require('path');

//declare static path
let staticPath = path.join(__dirname, "js");

//intializing express.js

const app = express();

//middlewares
app.use(express.static(staticPath));

//routes
//home route
app.get("/", (req, res) => {
res.sendFile(path.join(staticPath, "index.html"));
})

//signup route
app.get("/signup", (req, res) => {
res.sendFile(path.join(staticPath, "signup.html"));
})

// 404 route
app.get("/404", (req, res) => {
res.sendFile(path.join(staticPath, "404.html"));
})

app.use((req, res) => {
res.redirect('/404');
})

app.listen(3000, () => {
console.log('listening on port 3000.......');
})

index.html is the content of my webpage

<!DOCTYPE html>
<html>
    <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>Online Clothing Store - Best Apparel Collection</title;

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

    <body>
        <nav class="navbar"></nav>

        <!-- hero section-->

        <header class="hero-section">
            <div class="content">
                <img src="../img/light-logo.png" class="logo" alt="">
                <p class="sub-heading">best fashion collection of all time</p>
            </div>
        </header>

        <!-- card-container-->

        ...
    </body>
</html>

I am experiencing an issue where the CSS does not load when I run localhost:3000. The HTML loads fine but the styling is missing. How can I fix this? I am following a tutorial but the author and others don't seem to have this problem. Here is the link to the tutorial here.

Answer №1

When using

app.use(express.static(staticPath));
to declare a directory as static, it's important not to use the js directory for this purpose. Instead, consider creating a new directory such as public where you can store your css and js files.

By doing this, your css files will be accessible through the url /css/xxxx.css and your js files through /js/xxxx.js.

If you have any questions, feel free to ask!

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

Populate an array using a web API AJAX request in jQuery

I'm encountering an issue with jQuery or Javascript. My goal is to display additional flags in Google maps from an IP array. I've successfully passed the IP array to the function, but when I use ajax to call the web API multiple times correspondi ...

When executing a test using mocha, sinon, and chai, the error "res.status(...).json is not a function"

Hey there! I've encountered an issue with a failing unit test for a controller. Despite mocking the response object, the test keeps failing because of the json is not a function error and also due to the statusCode being undefined, when it's expe ...

Why is it that one of my useQuery hooks is returning a value while the other one is returning undefined?

I'm currently facing an issue with React Query where one of my useQuery hooks is logging undefined while the other one is displaying the correct data. Both functions are async and perform similar tasks. I've been troubleshooting this problem for ...

Is regex the reason why the website isn't showing up properly on mobile devices?

I encountered an issue on my Vue.js website hosted on Firebase where a blank white page was displayed on mobile devices. After some investigation, I traced the problem back to two objects declared in the data function of one of my components: re: { you ...

How can we make the Facebook like button display the fan count as the counter?

Can the Facebook like button be customized to display the fan count as the counter, and also update the fan count when clicked (like/unlike)? I've searched through forums and tutorials but haven't found a solution yet. It appears that the standar ...

Attempting to configure Kafka consumer and producer components

Trying to establish a basic producer-consumer flow with Kafka, utilizing node-rdkafka Operating in debug: 'all' mode, the logs display: Producer: test [0]: MessageSet with 1 message(s) delivered Consumer: Fetch topic test [0] at offset 38 (v2) ...

Techniques for dynamically displaying or hiding elements depending on various input groups using jQuery?

I am faced with a challenging task of handling multiple product forms on a single page. Each form contains various color options represented by radio buttons, each marked with either an available or unavailable attribute. My goal is to display a customize ...

nextJS does not recognize the term 'Window'

I'm encountering the error "window is not defined" in my NextJS project. The variable isMobile determines whether the window size is less than 767.98 to handle the hamburger menu functionality. This code worked in ReactJS but seems to be causing issue ...

unable to connect a value with the radio button

I am struggling to incorporate a radio group within a list of items. I am facing difficulty in setting the radio button as checked based on the value provided. Can anyone provide me with some guidance? Here is the HTML code snippet: <div *ngFor=" ...

The page fails to load when redirected, however, it briefly displays the page upon clicking the back button before navigating back to the previous page

Currently, I am working with Angular 2 and encountering an issue when attempting to click on a link. The loading bar continues to progress without displaying the data or HTML content on the page. Furthermore, if I try to go back to the previous page, the i ...

Running the command npm show --outdated triggers an E404 error stating that the package is not found in this registry

I am currently working on a confidential project that I prefer not to make public. Despite using node v17.3.0 and npm 8.3.0, I am facing difficulties in displaying the outdated dependencies: $ npm show --outdated npm ERR! code E404 npm ERR! 404 Not Found - ...

"Slow loading times experienced with Nextjs Image component when integrated with a map

Why do the images load slowly on localhost when using map, but quickly when not using it? I've tried various props with the Image component, but none seem to solve this issue. However, if I refresh the page after all images have rendered once, they ...

Exploring the functionality of v-chips within a v-text-field

I am trying to implement a search text field using vuetify's v-text-field, and I want to display the user input in a chip (such as v-chip or v-combo-box). However, v-text-field does not seem to support chips based on the documentation. Is there a work ...

Whenever I include "border:0" in the styling of my hr element, a significant number of hr elements fail to appear on the screen

I have been experimenting with using hr elements to divide sections of my web page. Here is a snippet of the CSS code I am using: hr{ content: " "; display: block; height: .1px; width: 95%; margin:15px; background-color: #dfdfdf; ...

Multiple file formats supported by Uploadify

I am trying to find a solution for having various file types in the jQuery plugin Uploadify. Consider this scenario: You want to open a file with a program of your choice. Starting with a default OS dialog, you can select different file types from a dropd ...

Error in Laravel npm package

Working on my Laravel project, I encountered an issue while trying to implement a video chat feature using https://github.com/PHPJunior/laravel-video-chat?ref=madewithlaravel.com with laravel-echo-server. Despite trying various solutions, none seemed to wo ...

The AudioContext feature is functioning properly on Google Chrome but experiencing issues on Safari

In Safari, I understand that audio context needs to be created after user interaction. Despite this knowledge, the code below still didn't produce the desired result. HTML <button onclick="play">Play</button> Javascript functio ...

The page remains static even as the function is executed

Having trouble with creating a sliding form using jQuery. The issue is that instead of sliding to the desired page, it slides to a blank one. The website where this problem can be seen is www.entrilab.com. Upon inspecting the element, there are no errors ...

Modifying Label text dynamically using jQuery on Click event

My website HTML contains the following code snippet: <script src="js/jquery.flexslider.js"></script> <script src="js/jquery.rings.js"></script> The contents of jquery.rings.js are as follows: $('input[type="image"]') ...

Changing the file path names for two images simultaneously within a single ExpressJS route

What is my current task :: I am working on an expressjs program that is responsible for moving the image from temp location to /public/images/ for a single image. The key name for the image is :: key I am using :: var file_name=req.files.key.originalF ...