Error: ExpressJs cannot locate the requested CSS file

Currently, I am delving into the world of expressJS and nodeJS in an effort to expand my skills. However, I've hit a bump in the road when the server fails to locate the CSS file (resulting in a 404 error) upon loading the HTML page. Surprisingly, the page loads without any styling when accessed through the server, but everything looks great when I open it directly. Here is my express and node file code snippet:

var http = require('http'),
    express = require('express');
    app = express();

app.get('/', function(req,res){
    res.sendFile(__dirname + '/index.html');
});

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

app.listen(3000);

The CSS link in the HTML file is as follows:

<link href="public/main.css" rel="stylesheet">

Here is the structure of my files:

  • FrontEnd(folder)

    • index.html
    • index.js

    • public(folder)

      • main.css

Having scoured the internet and read through the documentation, I still can't seem to pinpoint the issue. What could I be missing here?

Answer №1

Your understanding of how the static binding operates is slightly off. The code snippet below illustrates how it works:

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

This code tells express that any requests for resources on / without explicit routes defined should be resolved through the filesystem, specifically in the ./public directory.

For example, if a user requests /cats.git and express doesn't have a specific route for it, it will then search the ./public directory for a file called cats.gif and return it if found (or return a 404 error if not).

Therefore, the location of the directory in your filesystem doesn't matter to the user of your site. They will access resources using clean paths. For instance, if you have a file ./public/main.css that you want to serve as static content, your CSS link should be:

<link href="main.css" rel="stylesheet">

When a request for /main.css is made, express will see no explicit routes defined for it and will search for main.css in your static directories. It will locate ./public/main.css and return it as the response for /main.css.

Answer №2

Check out this piece of code:

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

HTML
<link href="main.css" rel="stylesheet">

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

What could be causing NPM to encounter difficulties when attempting to install bcrypt

When attempting to use bcrypt for salts and hashing through NPM installation, I encountered the following error message: gyp ERR! configure error gyp ERR! stack error spawn ENOENT gyp ERR! stack at errnoException <child_process.js:1001:11> gyp ERR ...

The ng-class condition is in flux, however, the new style is not being

Attempting to modify the background of the pane in an Ionic application based on the condition of the ng-class as shown. Changing the condition in the code and refreshing the page manually works correctly, but updating the condition from user input does ...

Fixing TypeError in React App: How to Resolve the "Cannot read property 'prototype' of undefined" Issue

I am completely new to JavaScript and I am struggling to understand the error that keeps popping up. After doing some research, it seems like the error could be due to a poorly written function or something along those lines. Here are the classes involved ...

Using background-image in Internet Explorer has always been a challenge

HTML <div id="banner" style="display: block; background-image: url('images/swirl_home.gif'); background-repeat: no-repeat; background-color: #e7e7e7;"> <div id="Hi"> some text here... </div> & ...

What is the reason behind fixing an overflow issue simply by moving the mouse outside of a container in IE7 and HTML?

My webpage includes a series of questions, with each question being displayed or hidden based on the answer to the previous question. Occasionally, after toggling back and forth between questions, I notice that the final question appears below its designa ...

It is impossible to add a promise's value to an array

When attempting to push values into an array and return them, the console only displays an empty array or shows undefined! The issue seems to be that .then does not properly pass the value to the array. const net = require('net'); const find = re ...

Closing a Javascript Websocket connection may result in server crash

I encountered an issue while trying to exchange data between my client and server. It seems that every time I closed my client, the server crashed... My server runs on Node.JS using the nodejs-websocket library. After some investigation, I discovered tha ...

Building a DataFrame from JSON data using danfo-js, mongoDB, and mongoose on a Windows 10 platform: A guide

I'm currently facing a challenge in constructing a DataFrame using danfo-js with JSON data retrieved from mongoDB / mongoose. Just to provide some context, the dependencies I am using are danfojs-node: ^0.1.5, mongodb: ^3.3.4, and mongoose: ^5.7.12. ...

Using MaterialUI to create a GridListTile with two IconButtons

I'm working with a GridListTile and trying to add a second button, but I'm having trouble getting both buttons to display. Even though I've attempted to include two ActionIcons, only one of them is showing up. Here's the code snippet: ...

Troubleshooting Java installation problem with NPM on Windows 10

Having an issue while trying to install Java using npm in cmd as administrator. Despite setting all environment variables, I am encountering an error. Any assistance would be greatly appreciated. Thank you in advance. gyp ERR! configure error gyp ERR! sta ...

Tips for concealing the CSS style of a descendant span element when the parent div employs text-overflow: ellipsis

Is it possible to prevent the green background of a child span from showing when the parent span has text overflow ellipsis applied? .container { border : 1px solid black; max-width : 100px; overflow : hidden; text-overflow ...

Utilize NodeJS to transmit data to a ZeroMQ cloud backend

Currently, I am delving into the world of ZeroMQ and practicing by recreating all the examples from scratch in the guide using NodeJS. However, I have hit a roadblock with one specific example that involves setting up a local cluster to process jobs and se ...

What is the method for adding a document within an array that is nested within another document?

Apologies if the title seems complex... I struggled to find a better way to describe it. The scenario I am dealing with fits the following Schemes: Collection1: const mongoose = require('mongoose'); const itemSchema = mongoose.Schema({ _id: ...

What is the best way to transform a GET request with a query string into a promise?

After successfully making a request with querystring params, I encountered an issue while trying to promisify my request: // Works var Promise = require("bluebird"); var request = Promise.promisifyAll(require("request")); request.get({ url: 'htt ...

Is there a way to use the command line (apk --update add) to install the most up-to-date version of node.js with the latest features, rather than the LTS version recommended for the majority of users?

My Docker file is based on 'python:alpine' image. I want to have both python and node.js installed in the container, so I begin with a python image. How can I install the most recent version of node.js ('Current latest features') in t ...

Encountering an issue with importing from 'sockjs-client' in TypeScript

I am a beginner with Angular and TypeScript. To get started, I used npm to install the following package: npm install --save sockjs-client I attempted to import it in my chat.component.ts file like this: import * as SockJS from 'sockjs-client'; ...

Decrease the size of the hyperlink area to only the center portion of the text for a more precise click target

Normal text links are present: <a href="projects.html">Projects</a> Is it feasible to make only the middle part of the letters clickable? Such as excluding the top of 'P' or the bottom of 'j'? a { font-size: 50px; ...

Can a rotation animation be incorporated into an image in next.js when it is clicked?

Looking to enhance a next.js image with an animation? How about making it rotate 360 degrees upon each click? Despite my attempts at toggling classes, I can't seem to achieve the desired outcome. Any guidance would be greatly appreciated. Thank you in ...

What steps can be taken to implement CSS rules on an HTML element with ExtJS?

In my ExtJS 4 project, I am working on drawing an image inside a panel and slider field. My goal is to adjust the opacity of the image based on the value of the slider field. I understand that I can use CSS rules like opacity and filter:alpha(opacity=); t ...

Switching the background image with a single click and reverting it back with a double click using jquery

I am working on a project with multiple div elements which need their background images to change upon clicking and revert back to the original image when clicked again. Below is the CSS code for one of the divs, including its Class and ID: .tab_box { wid ...