What could be the reason for Express not retrieving my external CSS file?

The console consistently displays the message:

GET http://localhost:8000/public/stylesheets/mystyle.css
.

Upon examining the image attached below, it is evident that this path is incorrect. I utilized WebStorm to create the href attribute for the CSS.

app.js

var     express = require("express"),
            app = express(),
     bodyParser = require("body-parser"),
       mongoose = require ("mongoose");

app.use(express.static("public"));
app.set("view engine","ejs");
app.use(bodyParser.urlencoded({extended:true}));

header.ejs

<html>
<head>
    <title>My Blog</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.9/semantic.css" type="text/css">
    <link rel="stylesheet" type="text/css" href="../public/stylesheets/mystyle.css" >
</head>

Project path : https://i.sstatic.net/H1uqD.png

Answer №1

If you have a static relative path within a shared HTML code snippet across multiple pages in various directories, it's best to steer clear of using "../" relative paths in href="" and src="" attributes. Instead, opt for root-relative / or server-generated application-root URLs, also known as "base" URLs. (For example, in ASP.NET this is achieved with ~/). Node.js currently lacks a built-in base URL feature, but there are third-party packages that can help with this.

For example, transform this:

< link rel="stylesheet" type="text/css" href="../public/stylesheets/mystyle.css" >

into this:

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

Furthermore, if your stylesheets directory only contains *.css files, consider using a directory named "styles" instead. This directory can house both .css files and other associated assets like images and fonts referenced by the .css files. This approach results in shorter URLs in CSS without the need for parent-relative paths. For instance:

foo#bar { background-image: url("../images/fooBg.png"); }

can be simplified to:

foo#bar { background-image: url("fooBg.png"); }

Answer №2

Utilize Express static to automatically locate your static files for you (assuming you have already set this up). Consider removing 'public' from your view URL, as shown below:

<html>
<head>
<title>My Blog</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.9/semantic.css" type="text/css">
<link rel="stylesheet" type="text/css" href="stylesheets/mystyle.css" >
</head>

Answer №3

If you're still encountering issues, it could be related to how you configured the static directory in your Express setup. The Express documentation explains:

It's important to note that the path you specify in the express.static function is relative to the directory where you started your Node.js process. If you're running the Express application from a different directory, it's best practice to use the absolute path of the directory you intend to serve:

To address this, you might need to define the absolute path to your public directory like this:

var path = require('path');
...


app.use('/static', express.static(path.join(__dirname, 'public')))

...
<link rel="stylesheet" type="text/css" href="/stylesheets/mystyle.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

Utilizing Jenkins Pipeline to Retrieve Environment Variables in Node.js Builds

I require assistance with configuring my Jenkins pipeline. My goal is to execute builds in a specific sequence: logging into a platform, deploying applications, and then logging out. These builds are written as nodejs scripts and utilize environment vari ...

unable to submit form using angular and express

I am encountering an issue with a post request in AngularJS to express. The HTML form on the client side is defined as follows: <div ng-controller="LoginCtrl"> <form ng-submit="login()"> <div> <label>Username</lab ...

How can I set up a cycling image background for the main div and a floating menu?

I was wondering how I could keep a cycling image background stationary behind the main content while scrolling through the page. You can check out the project itself by following this link. Feel free to use any of the code, including the fixed header menu, ...

Development versions of npm libraries

Lately, I came across a library called react-3d-components that offers some d3 react components with basic charts. It's an impressive collection of components. However, when trying to access the source code due to incomplete documentation, I found my ...

How can I locate an element within the body of an if statement?

I am working on a simple JavaScript (jQuery library) if statement to check for the presence of a div element with the class 'video' on the page. If it finds the element, the variable 'arrows' is set to true, otherwise it is set to false ...

Is it possible that running `npm run build` in a React app only builds the favicon.ico file?

I typically use https://github.com/facebookincubator/create-react-app for my boilerplate page. When I execute npm run build on my local MacBook, everything runs smoothly. However, when attempting to run it on my production server (Ubuntu on DigitalOcean) ...

Guide to making a language selection wrapper using a gist script

Currently, I have a Gist file that is written in various languages but all serve the same purpose. As a result, I am interested in developing a language selection feature similar to what is found in the Google docs documentation. https://i.stack.imgur.com ...

What are the best methods for creating genuinely random and highly secure session IDs?

I am looking to develop session middleware for Express, however, I am unsure about generating random and secure session IDs. How do larger frameworks like Django and Flask handle this issue? What would be the best approach for me to take? ...

Loading HTML file using XMLHttpRequest

I am currently developing a website using HTML, CSS, and JavaScript. The project follows the usual structure with multiple HTML files (such as Index.html, Footer.html, Whatsapp.html), styles.css, and app.js. Within my Index.html file, I include the styles ...

Encountering difficulties integrating Bootstrap with Angular CLI project

I am facing an issue while trying to integrate Bootstrap 4 RC6 into my Angular CLI project. Despite following the necessary steps, I am encountering an error that I cannot quite explain. Here is a detailed overview of what I did to create the project: Fir ...

Generating swagger documentation for TypeScript-based Express applications

I have successfully set up the swagger URL following a helpful guide on configuring Swagger using Express API with autogenerated OpenAPI documentation through Swagger. Currently, I am utilizing TypeScript which outputs .js files in the dist folder without ...

Having trouble with testing an Angular directive?

This is a snippet from my directive spec file for Angular 6. import { Component, DebugElement, NO_ERRORS_SCHEMA } from '@angular/core'; import { TestBed, ComponentFixture, async } from '@angular/core/testing'; import { By } from ' ...

Calculate how frequently an element showcases a particular style

I attempted to tally the occurrences of a specific class on an element, but I keep encountering the error message: $(...)[c].css is not a function Does jQuery have it out for me? Below is the code snippet in question: // hide headings of empty lists le ...

What security measures does Angular implement to safeguard against malicious user input?

While I was learning how to build a router in vanilla JS, the tutorial author mentioned that it's advisable to use frameworks like Angular or React for various reasons. The author pointed out that Angular, for example, sanitizes user input before inse ...

Using the shift() method in Javascript to manipulate Objects

My goal is to take my list and combine the first two items (0 & 1) together. I attempted the following code: total=foo.shift(); foo[0]=total However, I encountered this error: Uncaught TypeError: Object [object Array] has no method &ap ...

Calling Functions in JavaScript Through Events: A Beginner's Guide

As I dive into learning JavaScript, one thing that stumps me is figuring out how to call a function from an event. Currently, the only method I am familiar with involves using anonymous functions (as seen in my code example below), but I'm curious if ...

Performing an HTTP request using the Cntlm proxy

I've been attempting to send an HTTP request through a Cntlm proxy in NodeJs, but I'm having trouble getting it to function. Below is the code I've written: var http = require('http'); var options = { host: 'http://127.0.0 ...

When attempting to update my avatar using client.user.setAvatar(), the desired changes fail to take effect

Currently, I am attempting to update the bot avatar with a specific user's avatar, but I seem to be encountering some difficulties. I have attempted the following code: client.users.fetch('userid').then((user) => { client.user.setAva ...

Attempting to move elements into an array for storage in the local storage

Is there a way to properly add elements to an array and store it in localstorage? Here's the code snippet I've been working with: const handleSelectLayouts = (layout) => { const layoutsArray = []; layoutsArray.includes(layout) ...

Gradually returning to the top with Vuetify's smooth scroll feature

Looking for a way to make the scrolling back to the top of the page smoother on my website. The button I currently have in place does the job, but it's not as smooth as I would like. Any suggestions on how to improve this? I've checked similar q ...