Express.js problem: Unable to load CSS and JS files from the 'public' directory

Currently, I am working on a web project with Express.js and encountering difficulties in loading CSS and JavaScript files from the 'public' folder. Despite following common practices, it seems that something is amiss. Here is the layout of my project:

  • public

    • style.css

    • script.js

  • views

    • index.ejs

    • AboutMe.ejs

    • ContactMe.ejs

  • Other Express.js files (app.js, routes, etc.)

My EJS templates include links to my CSS and JavaScript files using the following format:

<link rel="stylesheet" type="text/css" href="/styles/style.css">
<script src="/scripts/script.js"></script>

However, my pages are not applying styles and scripts as expected. I have checked the file paths, and they appear to be correct.

Is there a specific configuration required in my Express.js application to ensure proper serving of files in the 'public' folder? Despite trying different approaches and searching for similar issues, I have yet to find a solution.

I would greatly appreciate any guidance or suggestions. Please let me know if more information about my project setup or configuration is needed.

Thank you for your assistance!

Attempts Made:

I have double-checked both the file paths and location of my style.css file. I have verified the usage of correct paths in my EJS templates. I have confirmed that the express.static middleware is properly configured.

Expected Outcome: My expectation is for the CSS styles to apply correctly to my EJS templates when loading my Express.js app

Answer №1

If you have CSS and JS files in the same folder but want to serve them via separate paths such as styles and scripts, you can achieve this using the static middleware.

app.use(["/scripts", "/styles"], express.static("public"));

With this setup, URLs like /styles/style.css, /styles/script.js, /scripts/style.css, and /scripts/script.js should all work correctly.

However, a more common practice is to organize static assets into their respective sub-directories within a main public directory and serve the entire directory statically:

.
└── public
    ├── scripts
    │   └── script.js
    └── styles
        └── style.css
app.use(express.static("public"))

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

Steps for populating a dropdown list with a JSON response

I'm facing a challenge in inserting server data into a dropdown list because each object name begins with a random ID. Here's what I'm attempting to achieve here: $("#CampaignOpenActionSubscriber_campaign_id").change(function() { var el ...

Incorporating unique typography onto your website (HTML/CSS)

I am currently struggling to implement a custom font on my website. I'm not very experienced with programming, and since my friend isn't available to help, I'd appreciate a solution from anyone. The issue I'm facing is that while the Ca ...

Sideways movement of a single line within a table

Would you please help with a challenge I'm facing? I want to create a horizontally scrollable row that spans 100% of the page width without overflowing on top of the background image and while keeping the header text in focus. This is what I have att ...

Displaying JSON keys and values individually on an HTML page

Looking to display a JSON array in HTML using ngFor TypeScript : import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-ng-for', templateUrl: './ng-for.component.html', styleUrls: ['./ng-for ...

Error encountered in Three JS Drag Controls: Unable to assign value to property 'x' as it is undefined

I've been trying to drag the spheres around the scene using drag controls that should be activated when the "m" key is pressed. However, I keep running into an issue where the objects don't move and I receive an error message saying "Uncaught Typ ...

Is there a way to freeze a row in Bootstrap 4?

I recently put together a slider featuring four images, but I've encountered an issue. When the pixel size drops below 768px, the image quality diminishes and they start stacking on top of each other. Is there a way to keep the images in a single row ...

Typescript-enabled NodeJS REST client

I'm currently working on a nodejs web application using express and I want to access my API. I have experimented with various options, such as restangular and jquery ajax calls. Can anyone recommend some reliable REST client libraries with TypeScrip ...

Is there a way to customize the Master Page in asp.net to resolve the Bootstrap4 dropdown issue? I am encountering an error message that says "Uncaught TypeError: Bootstrap

Hello everyone, I recently encountered an issue while trying to use dropdown in my project after updating to bootstrap 4. It was working perfectly fine before the update, but now I'm getting an error in the JavaScript. The error that pops up when I tr ...

Using PHP to dynamically update image source upon clicking an upload button:

Is it possible to dynamically display a new image after uploading it using an ajax-upload script on a 'edit product' page for a shop products? On load, all thumbnails are fetched from the DB but when a user uploads a new file, I want the new imag ...

How can a pop-up be positioned to appear in the right bottom corner using jQuery

Is there a way to position a pop-up at the bottom right corner of the window? I have code that centers the pop-up in the window, but I'm looking to place it specifically at the bottom right corner. $(id).css('top', winH - $(id).height()); ...

Storing items in localStorage in the same order they were added

I am having an issue with sorting localStorage items by the order they were added. Despite my code working to add items to the localStorage array and display them as HTML, I am encountering a problem with the order of the items. When I add a 3rd item to t ...

Replacing text within a paragraph using D3.js

Is it possible to develop a D3 function that can choose a paragraph, delete its content, and replace it with new text? If so, what would be the most effective way to accomplish this? I attempted the following: d3.select("#triggerButton") .on("clic ...

Choose does not showcase the updated value

My form contains a form control for currency selection Each currency object has the properties {id: string; symbol: string}; Upon initialization, the currency select component loops through an array of currencies; After meeting a specific condition, I need ...

Importing an image from the public folder in a nested directory with Next.js

My images are stored in the public directory and all of my code is located in the src folder. Usually, when I try to import an image from src/page/page.js like: /image/logo/logo-dark.png, it works. But when I am importing images from the src/component/cor ...

Issue with Three JS where the BoundingBox does not update correctly following rotation operations

I am trying to determine the bounding box of a geometry after applying rotations to it. I obtained the rotation code from the sample editor in Three JS: object.rotation.x = xRadians; object.rotation.y = yRdians; object.rotation.z = zRadians This rotatio ...

Unexpected behavior observed with field alignment

I've been attempting to align the field in an Angular HTML page, but it's not working out as I expected. Here's how the HTML file looks: <div id="report-prj-search"> <div class="dx-fieldset flex-column"> <div class="fle ...

Angular 4 with Typescript allows for the quick and easy deletion of multiple selected rows

I am currently working on an application where I need to create a function that will delete the selected checkboxes from an array. I have managed to log the number of checkboxes that are selected, but I am struggling to retrieve the index numbers of these ...

Show or hide a Div based on radio button selection problem

I've successfully implemented a Div visibility toggle using the code below: $('input[name="type"]').on('change', function() { var show = $(this).val(); $(".typechoice").hide(); $("#"+show).show(); }) <script src="h ...

Trigger a function in JavaScript by clicking on an element and passing its class

I have written the following code: <?php $extCount = 0; foreach($this->externalReferal as $externalReferal) { $extCount++; ?> <div class='fieldtestPct' > <div class='fieldItemLabel'> < ...

"I'm encountering an issue with the discord.js module when I try to launch my bot using node. Any ideas on how

I encountered an unusual error with my Discord bot recently. It seems that discord.js crashes every time I try to run my bot: [nodemon] 2.0.12 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mj ...