Delivering seamless css integration using express.js

Lately, I've been struggling with serving CSS using Express.js. After some trial and error, I managed to make it work. However, I'm puzzled as to why my new code works while the old one doesn't. Here's the code that now works for me:

const express = require('express');
const path = require('path');

const app = express();
const port = process.env.PORT || 5010;

console.log(__dirname)
app.use('/public', express.static('public'));
app.set('views', path.join(__dirname, 'views'))

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'views', 'home.html'));
});

app.listen(port, () => {
  console.log(`Server started on port ${port}`);
});

This is how my file system is structured:

index.js
public
  css
    home.css
views
  home.html

Instead of my previous code:

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

I had this working version:

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

Could you explain why the second version works but not the first one? What role does the first parameter play in the second version? Just so you know, I'm coding on replit.com.

Answer №1

How to Serve Static Files in Express

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

This code allows you to serve files located in the "public" subdirectory of your current directory. For example, if you have a file at public/css/home.css, you can access it using the URL: http://localhost/css/home.css

Adding a Virtual Path Prefix

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

By adding a virtual path prefix "/public", you can now access the same file at public/css/home.css using the URL:

http://localhost/public/css/home.css

You can customize the first parameter to anything you like. For instance, changing it to '/static' would change the URL to:

http://localhost/static/css/home.css
.

For more detailed instructions, refer to the official documentation here

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

Error in jQuery when element is not found

On my website, I use multiple jQuery functions, but not all of them are necessary on every page. These functions are all located in one XXX.js file, such as: jQuery(function() { $(".title").slug({ slug:'slug', hide: false }); }); ...

Issue with fixed positioning on iPad devices

A unique feature we implemented on our site is a small control that is positioned at the bottom of the screen. However, upon viewing the site on an iPad, the control does not stay fixed at the bottom but rather floats in the middle. What's the issue ...

Adding a cell break line within AG-GRID in an Angular application

I'm trying to display two sets of data in a single cell with ag-grid, but I want the data to be on separate lines like this instead: Data with break line I attempted to use "\n", "\r", and "\br" but it didn't work. Here is my code ...

Why does Math.max.apply not prioritize the first parameter?

function findSmallestNumber(numbers){ return Math.min.apply(Math, numbers); } This code sets the context to be the Math object. However, this is not required because the min() and max() methods will still function properly regardless of the specified co ...

What is the optimal unit to employ in CSS - percentages or pixels?

As someone who is not well-versed in CSS, I strive to create a design that will appear visually appealing across all browsers and screen resolutions. I have observed that certain websites construct their designs using percentages for properties like width, ...

Converting ed25519 private key into OpenSSH Format using JavaScript

After generating an ed25519 key pair using the javascript crypto library, I am now faced with the challenge of saving the private key in openssh format. Despite attempting to use the sshpk library for this task, I encountered an issue where the exported k ...

How to send a function from a parent component to a child component in Vue.js

I'm trying to figure out how to pass the parent component's method to the child component. Here's the scenario: when I click the confirm button on my modal (child component), it needs to send the data from the parent form (parent component). ...

Exploring the possibilities: Utilizing HTML5, File API, and jQuery to

I have a form displayed in a dialog and it includes a "submit" button which, when clicked, utilizes jQuery to send the form data to the server via AJAX. However, I encountered an issue where the uploaded file was always null. After researching on Google, I ...

Time-driven occurrences in HTML

I want to create a daily event, like an alert box or a message displayed in a window, at 10 am on my webpage. How can I achieve this without constantly checking the time and wasting resources? ...

Encountering a type mismatch error in Typescript while working with Redux state in a store file

It appears that I have correctly identified all the types, but could there be a different type of Reducer missing? 'IinitialAssetsState' is not assignable to type 'Reducer' The complete error message: Type '(state: { assets: n ...

When attempting to render a React child, it is important to note that objects are not valid (found: [object Promise]). If your intention was to display a collection of children, it is advised

Instructions in "/pages/blog/index.js" : import BlogComponents from "../../components/Blog/blogComponents"; import { listBlogs } from "../../server/mongodb"; const index = async (props) => { console.log(props) return ( ...

What is the best way to leverage local storage/memory to save information for my text-based RPG game?

Currently, I am in the process of creating a text-based RPG on Codecademy. However, I am facing a challenge when it comes to implementing a save/load system using JavaScript/HTML. My idea is to create a system where players can type "save" into a prompt, ...

Building a custom dialog box using Angular Material with HTML and CSS

I've been exploring different approaches to create a customized angular material dialog with a unique header using CSS/SCSS and the TailwindCSS framework. I am aiming for a specific visual effect, similar to what is shown in the figure below. desired ...

How can I collect various values from input fields that are within a foreach loop using jQuery?

<script> $("#submit").click(function(e){ e.preventDefault(); subjectID = $("#subjectID").val(); subject = $("#subject_"+subjectID).val(); subject_code = $("#subject_code_"+subjectID).val(); internal_marks = ...

Using JQuery to compare duplicate values within the same input name

I am dealing with several hidden input fields like the ones below: <input type="hidden" value="4531" name="product_id"> <input type="hidden" value="4532" name="product_id"> <input type="hidden" value="4533" name="product_id"> My goal is ...

submit the JSON formatted data to the server

I am attempting to extract data from a form and transmit it to a remote server: Below is the code snippet: <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"></script> </head> ...

A guide on generating indices for icosahedronbuffergeometry using three.js

I am facing an issue and struggling to find a solution. I am looking for an alternative method to texture a sphere in three.js by using icosahedronbuffergeometry instead of spherebuffergeometry with additional code to generate indices for rendering using d ...

Running a designated AJAX function from a variable by utilizing Applescript

Struggling to execute a JavaScript code within a page using Applescript. In the JavaScript, an AJAX function was defined like so: var myFunction = function () { // Here be the code... } I attempted this in Applescript: do JavaScript "document.myFunct ...

Creating dynamic scroll animations for sidebar navigation in a single-page website with anchor links

I need help creating a seamless transition between anchor points on a single page, while keeping a fixed navigation menu that highlights the active section. As a novice, I am unsure how to incorporate "( document.body ).animate" or any other necessary code ...

Designing an image transformation page by segmenting the image into fragments

Does anyone have insight into the creation process of websites like this one? Are there any plugins or tools that can assist in building something similar? ...