What is the best way to load my CSS file using express.static?


How do I properly load my CSS file using express.static in Node.js? I have attempted various methods to link my stylesheet to my HTML file through Express, and I'm also interested in learning how to include images, JavaScript, and other assets to create a more dynamic website. Despite trying multiple solutions, I haven't been able to find the right one.



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

app.use(express.static(__dirname));

getId = (req, res) => {
       const id= req.params.id * 1;
        res.sendFile(`${__dirname}/index.html`);
}

app.get('/hibiscos/:id', getId);

const port = 8000;

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

Answer №1

If you include

app.use(express.static(__dirname));
in your code, all the files located in the current directory can be easily accessed using /. Simply place your .css, .js, and other static files in the same directory, and then retrieve them by adding / followed by the file name - like /style.css, /image.png, /script.js, etc.


In this context, the term "current directory" refers to the value of __dirname

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

utilize dynamic variable within the template's views

Here is a snippet of my HTML code var marker; function initMap() { map = new google.maps.Map(document.getElementById("mymap"), myOptions); getMapMetadata([]); // setInterval(function(){ getMapMetadata([]); }, 3000); } function createMarke ...

The images on the carousel fail to load unless I adjust the window size

After investing countless hours into finding a solution, I am still unable to resolve this issue. The problem lies within my use of a Carousel and setting the images through a javascript file. Strangely enough, upon loading the page, only the first image ...

npm audit fix failing to reflect changes in package.json

After numerous attempts, I have finally found a fix for one vulnerability using npm audit fix. The npm audit report indicates: # Run npm update mkdirp --depth 8 to resolve 10 vulnerabilities ┌───────────────┬── ...

Having trouble getting THREE.Raycaster to intersect with THREE.PointCloud

Currently, I am trying to implement click events on my WebGL based 3D graph library called Graphosaurus. You can take a look at what I have done so far here. I have used this example as a reference. I am wondering if the reason it is not functioning corr ...

Using the Strikethrough Feature in React

Is it possible to apply a strikethrough effect to a checkbox's label text when toggled on and off? In my system development process, I've utilized various methods. What modifications should be made in the fComplete method for this feature to wor ...

Tips for identifying text within HTML code

Looking for help with this HTML code: <span class="navbar-text navbar-nav company-title">aLine</span> The text "aLine" is displayed on the navigation bar. Can you guide me on how to locate this text using xpath? ...

Tips on causing a div to overflow instead of wrapping onto a new line

Are you looking to design a slider with 3 image containers all in the same row, where the third one overflows instead of wrapping to a new line? Here is an example: Desired Design: https://i.stack.imgur.com/dKyEg.png Current State: https://i.stack.imgu ...

As you scroll, the opacity gradually increases, creating a dynamic visual

Struggling to replicate a feature on a website where images gain opacity as you scroll down? Check out this site for reference: . While my current code somewhat achieves this effect, I'm having trouble figuring out how to apply a darker opacity gradua ...

Activating the submit button only following confirmation that the image dimensions have been verified

I've written some code that checks whether selected pictures meet specific size and dimension constraints before enabling the submit button. However, there's an issue where the button might be enabled before verifying the last image due to delays ...

The problem of border-radius bleeding in Webkit when applying -webkit-transform

After creating a basic jQuery script to slowly rotate an image, I encountered an issue where the rotated image would bleed over the border-radius in Chrome. The rotation works smoothly in Firefox 4.0.1 but not in Chrome. To see the example and code, check ...

Discovering duplicates for properties within an array of objects in React.js and assigning a sequential number to that specific field

I am working with an array of objects where each object contains information like this: const myArr=[{name:"john",id:1}{name:"john",id:2}{name:"mary",id:3}] In the first 2 elements, the "name" property has duplicates with the value "john". How can I updat ...

Unable to hear sound on Mozilla Firefox

I am facing an issue with playing an audio file using the audio tag inside the body element. The audio plays perfectly in Chrome once the body has finished loading, but it fails to play in Mozilla Firefox. I even attempted to download the audio file and pl ...

Is it feasible to create a full-page text gradient clip without it repeating on each individual element?

.gradient { background-color: #00ccaa; background: linear-gradient(0deg, #00ccaa, #f530a9); background-size: cover; background-clip: text; box-decoration-break:slice; -webkit-background-clip: text; -webkit-text-fill-color: transparent; -web ...

Retrieve an image from an external web service and transfer it to a different route in Express.js

I am facing an issue with passing an image object from an external web service through a node express route. The specific problem I am encountering involves retrieving an image from a URL and attempting to pass it as is, but it seems to be not functioning ...

Programming with a combination of Javascript, Angular, and Prototype to efficiently manage and

I am in a bit of a quandary, as I wish to create a function that will clear all the properties of an object and make it available to all instances of that object. To achieve this, I have added a prototype function called clear(). Here is the code snippet: ...

Unable to transmit form information using HTML/JavaScript/Express Node application

I'm facing a challenge in developing an app that allows me to input event information and then display it on a map. I'm encountering difficulties at the initial stage when it comes to saving the data. Even though Chrome's Inspect tool indica ...

Web scraping with Cheerio in Node.js sometimes yields undefined results

When attempting to extract data from NSE website, I initially tried using the inspect element console: (Edited the question) objs = $('div[class="table-wrap"] > table > tbody > tr > td').slice(0, 8) objs.map((i,element) =& ...

Guide to displaying Fontawsome icons with CSS2D Renderer/Object

I am trying to display the map-marker-exclamation icon from the FontAwsome library on top of a three.js cube, but unfortunately, the icon is not rendering properly. Can someone guide me on how to successfully render a FontAwsome Icon using three.js? Thank ...

Using express-boom for badRequest in your application is a simple and effective

Recently, I've started working with node+express and decided to incorporate the express-boom module into my project. While browsing through the official Express website, I came across the following snippet that caught my attention. However, I'm u ...

Is combining form and fieldset causing issues?

My <form> for uploading an image and my <fieldset> for sending data via AJAX both work individually. However, when I try to merge them into one form, things get complicated. This is being done on a Node.JS server. Upload <form>: <for ...