Utilizing Express for hosting public static resources

I am having trouble configuring my Express server to serve files from the public folder. Despite trying various file path combinations, Pug does not seem to cooperate with Node.js. While I can view the HTML content of the index, the CSS and music files fail to load. I have read multiple similar questions, but still cannot figure out why it's not working. Any assistance would be greatly appreciated.

These are the errors I receive in the developer tools: Refused to apply style from 'http://localhost:3000/public/music.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. GET http://localhost:3000/public/Music/Pink_Floyd/WishYouWereHere/ShineOnYouCrazyDiamond(PartsI-V).mp3 404 (Not Found)

This is how my file structure looks:

js

-server.js

public

-Music

--artist

---album

----musicfiles.mp3 

-music.css 

views

 -index.pug

Here is my Node.js code:

var jsmediatags = require('jsmediatags');
var express= require('express');
var app=express();
var pug=require('pug');
const path=require('path')
const fs=require('fs');
const { error } = require('console');
var tagsArray=Array();

const port=3000;
const host='localhost';

app.use('/public', express.static(path.join(__dirname, 'public')))
app.set('views','./views');
app.set('view engine', 'pug');

const server =app.listen(port, host, ()=>{

  console.log("server started at "+host+" port:"+port);

  
});

process.on('SIGTERM', () => {
  server.close(() => {
    console.log('Process terminated')
  })
})


jsmediatags.read("./public/Music/Pink_Floyd/WishYouWereHere/ShineOnYouCrazyDiamond(PartsI-V).mp3", {
  onSuccess: function(tag) {

    
    var tags=tag.tags;
    tagsArray=[tags.artist,tags.track,tags.album,tags.title,tags.picture];
    var artist=tags.artist;
    var album=tags.album;
    var title=tags.title;
    var track=tags.track;
   
      var base64Url=Buffer.from(tags.picture.data).toString("base64");

    // var base64Url=Buffer.from(base64String).toString("base64");
    var artInfo="data:"+tags.picture.format+";base64,"+base64Url;
    
    console.log(`data:${tags.picture.format};base64,`);

    app.get('/', (req, res)=>{

      res.render("index", {
        artist:tags.artist,
        album: tags.album,
        title: tags.title,
        track: tags.track,
        art: artInfo
        
      });
      console.log('done');
    });


  },
  onError: function(error) {
    console.log(':(', error.type, error.info);
  }
});

This is my Pug code:

html(lang="en")
    head
        meta(charset='UTF-8')
        meta(http-equiv='X-UA-Compatible' content='IE=edge')
        meta(name='viewport' content='width=device-width, initial-scale=1.0')
        title Music App
        link(rel='stylesheet' type='text/css' href='/public/music.css')
    body
        img#albumC(src=art alt='album art')
        .playbox
            .play
            .reflect
            .playRef
        .pausebox
            .pause
                .PA.center
                .PB.center
            .reflect
            .pause
                .PAref.center
                .PBref.center
        .stopbox
            .stop
            .reflect
            .stopRef
        h2 Artist: #{artist}
        h2 Album: #{album}
        h2 Song: #{title}
        h2 Track: #{track}
        audio(controls src="/public/Music/Pink_Floyd/WishYouWereHere/ShineOnYouCrazyDiamond(PartsI-V).mp3")

Answer №1

Based on the layout of your project directories, it appears that the public directory is located at the same level as the js directory where server.js resides, rather than being a sub-directory. In order to properly serve static files from the public directory, you need to adjust your code like so:

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

This change allows you to navigate up one level and then locate the public directory.

By making this adjustment, it aligns with the reference you have in this tag:

link(rel='stylesheet' type='text/css' href='/public/music.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

How can you determine if a domain belongs to Shopify when given a list of 98000 domain names using Node.js?

Is there a way to determine if a domain is operating on the Shopify e-commerce platform? I have been searching extensively but haven't found a reliable method. I possess an array containing 98,000 domain names and I am interested in utilizing node.js ...

Display a specific tab section upon clicking using jQuery or JavaScript

Hello everyone! I am completely new to JavaScript. I have added a tab slider to my HTML with 3 categories in the tab menu: All, Creative, and Branding. How can I show a div after clicking on one of the list items? I have assigned classes to the list items ...

Creating a simulated third-party service in NodeJS

Whenever a request is made to an example endpoint, another request is sent to a third-party service that can sometimes malfunction. To ensure relevant testing, I need to simulate this third-party service dysfunction in my tests. it('should handle mal ...

If the text width of a label exceeds the total width of its container, intelligently display a sub-string based on pixel calculations

I am looking to shorten the text inside a label if its width exceeds the total width of its container. Instead of displaying the full text, I want to display a sub-string of it. if (SensorType.Text.Length >= 25) { SensorType.Text = SensorType.Text ...

Having trouble with your Bootstrap 4 Dropdown Menu?

I attempted to implement the dropdown menu example from Bootstrap 4, but unfortunately it does not seem to be working as expected. The dropdown menu does not appear when clicked. <li class="nav-item dropdown"> <a class="nav-link dropdown-to ...

How can I duplicate or extract all the formatting applied to a specific text selection in Ckeditor?

I am currently utilizing CKEditor version 3.6 within my Asp.net MVC 3 Application. One of my tasks involves creating a Paint format option similar to Google Docs. I am looking to integrate this feature into CKEditor. Is there a way in CKEditor to transfe ...

The text is not rendering properly, with some characters being replaced by different ones

RESOLUTION: To fix the issue, eliminate font-family, font-size, and color properties from the parent div. UPDATE: The problem only occurs when I press CTRL + F5. UPDATE 2: After investigating, I found that the culprit is .site-footer with a position:abso ...

Utilizing the overflow feature in conjunction with a specified height

Take a look at this image, the overflow:hidden property is not working as expected and some text is still visible that I want to hide without adjusting the height. How can I achieve this? Focusing on the highlighted area in Red, it is causing irritation. ...

What is the point of serializing a user when I am already using tokens for authentication with Passport?

My application solely relies on passport-google-oauth20 for authentication. The process of authenticating a user and storing them in the DB using the verify callback provided by passport is working smoothly. In this specific app, I will strictly use Googl ...

Locate elements within an array where a specific attribute includes the specified search term

While working with Javascript, I encountered an issue where the function I wrote to retrieve objects from an array was not returning all the data that met the query criteria. In my dataset, which originally contained 1536 objects, there are several jokes ...

npm installation of prerender failed due to inability to locate: CL.exe

Having some trouble getting PreRender.Io set up on my local machine for testing. I've already installed Python 2.7.10. However, when I try to run: npm install prerender I encounter an error: C:\PreRender\node_modules\prerender\n ...

An error occurs when attempting to use Socket.io without explicitly returning the index.html file

I want to implement WebSockets without needing to return the index.html file. As someone new to Socket.IO, here's what I've attempted: First, I installed Socket.IO using npm: npm install socket.io --save Then, I created a file called index.js ...

What strategies can be used to manage data grouping requests by date that span across different time zones?

Imagine this situation: my server is running on a MySQL/NodeJS/Sequelize stack, and there's a specific request I need to carry out. The request returns anywhere from 1000 to 2000 entries, but all I really want is a condensed summary of these entries ...

Arrangement of elements across rows and columns in a grid pattern

Is it possible to span a column that is equivalent to two columns in the first row and then have one column each for the second row, as shown in the screenshot? (There are two columns in the second row in this case) CSS main section { display: grid; ...

Tips for extracting the data attribute value in node.js by submitting a form using the post method

How can I extract the value from a data attribute in Node.js via form submission? I need to collect additional information from the user! Here is what I attempted initially: Client-side: input(type="submit" ,name="responseValue" , value="yes", data="qu ...

There seems to be a problem with the routing using the ID parameter as the link is functioning, but

I am encountering an issue with retrieving the stored data from MongoDB using an :id parameter. The link functions correctly and directs me to the specified URL (./contests/1), but the data is not displaying. When I query within the mongo CMD with (db.cont ...

Node.js halted execution of NPM command due to insufficient memory

Just started working with nodejs and encountered some errors when using the npm command: $ npm install express --save Error: ENOMEM: not enough memory, scandir '/home/buraqtechno' <--- Last few GCs ---> [32765:0x23f0eb0] 216 ms: Mark ...

Emphasizing sections using a specific class for paragraph highlighting

Is it possible to dynamically change the style of paragraphs based on certain classes? Let's say we have a text with a list of p elements and we want to modify the styles of paragraphs that come after specific classes, such as 'alert' or &ap ...

Steer clear of altering line spacing in CSS

Here is the HTML structure that I am working with: <div id="id1"> <h1>my name </h1><h3><a href="mailto:myemail_id"><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff92869a929e9693969bbf878685d19 ...

Combining NodeJS with Javascript for wrangler bundling: A guide

The challenge: My goal is to create a Cloudflare worker that utilizes NodeJS dependencies. Unfortunately, I'm facing obstacles with Wrangler, preventing me from deploying it using the command wrangler deploy. The obstacle: X [ERROR] Could not resolve ...