There seems to be an issue with the CSS file linking properly within an Express application

Every time I run my app.js file, the index.html file is displayed. However, when I inspect the page, I notice that the CSS changes are not taking effect. Strangely, if I open the HTML file using a live server, the CSS changes are visible. Can someone explain why this difference in behavior occurs?

Answer №1

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

To implement this feature in your app.js file, you need to create a folder named public and place the style.css file inside it. Your code should look like this:

    const express = require('express');
    const path = require('path');
    const app = express();
    
    app.set('view engine', 'ejs');
    app.set('views', path.join(__dirname, 'views'))


    app.use(express.static(path.join(__dirname, 'public'))); // Make sure to add this line


    app.get('/', (req, res) => {
        res.sendFile(path.join(__dirname, '/index.html'));    
    });
    
    const port = process.env.PORT || 5000;
    app.listen(port, () => {
        console.log(`Server is running on port ${port}`)
    })

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

Move on to the next iteration in the FOR loop in Node JS

Is there a way to skip item 3 in the loop without breaking it? for (var i = 1; i<= 9; i++) { if (i==3) break; console.log(i); } I had a tough time searching for an answer online because I am unsure of the exact terminology to use. Desired output: ...

PapaParse is not properly recognizing the date format

Having trouble creating a chart using JSON data from papaparse, resulting in the following error: c3.js:2100 Failed to parse x '10-18-2018' to Date object I've tried adjusting the date format in the CSV file but haven't had any luck. I ...

How to Restrict the Use of Conditional "If" Statements in Another Function in Angular 7

How can I use an IF condition inside a function to only execute once for a specific action and not for another action? I have a function that is called twice, but I want the first "IF" condition inside the function to only be triggered when the add bank b ...

Obtain user input and showcase it on the screen using a combination of Ajax and PHP

Whenever a user inputs a value in the textbox, it should dynamically display on the screen. I have successfully implemented this feature once, but I am encountering difficulties with implementing it for a second input. Your help is greatly appreciated. fu ...

What is the method for retrieving the values of multiple numbers entered in table rows using ASP?

I am trying to customize an input field so that the client can add or delete N number of input fields as needed. While I have successfully implemented adding input fields, I am facing difficulty in retrieving values from these dynamically added text fields ...

Is it possible to execute an npm command within a docker container?

I am facing an issue while attempting to run my Angular application in development mode within a Docker container. When I use docker-compose build, everything works fine, but when I try to start the container, I encounter the following error: ERROR: for ...

File not found when attempting to copy file

Currently, I am facing an issue with installing both Python and Node.js within the same image. The problem arises when attempting to copy the package.json file, resulting in an error message stating no such file or directory, open '/opt/app/src/packag ...

Error message appears when trying to access the onSubmit property of undefined in mapped data containing buttons

Currently, I am developing a full stack application that pulls questions from my SQL server and displays them on the front end. Each question comes with an accept and decline button, and I need these buttons to trigger different responses in my database. ...

Why is it that injecting javascript within innerHTML seems to work in this case?

According to the discussion on this thread, it is generally believed that injecting javascript in innerHTML is not supposed to function as expected. However, there are instances where this unconventional method seems to work: <BR> Below is an examp ...

Retrieve all string values from an Angular POST request using Express

Here is a simple code snippet that sends a POST request to a server using express: $http.post('/blah', { boolean: true, stringBoolean: 'true', number: 213, stringNubmer: '44444444', string: 'adssd&apo ...

`<div>` element with a class of "button" that listens for

I've been attempting to use a userscript to automate a button click. Inspecting the element reveals the button code as: <div class="q-w-btn cl"></div> Unfortunately, the button lacks an id attribute, making it difficult for me to select ...

Is it true that outerHeight(true) excludes margins?

As stated in the JQuery documentation, the outerHeight(true) function should return the complete height of an element, including padding, border, and margins. However, I encountered a scenario where this functionality seemed to be flawed. You can find a co ...

"Adjusting the size of a circle to zero in a D3 SVG using Angular 2

Trying to create a basic line graph using d3 in Angular 2 typescript. Below is the code snippet: import { Component, ViewChild, ElementRef, Input, OnInit } from '@angular/core'; import * as d3 from 'd3'; @Component({ selector: 'm ...

What happens to a MySQL pool connection when it is released? Does keeping the connection open have any impact on the maximum number of connections in

My recent experience with MySQL has raised a perplexing query that I cannot easily resolve without further investigation. Upon creating and releasing a pool in MySQL, I noticed that an active connection persists in MySQL Workbench until the process is clos ...

fluid columns gliding from side to side

I'm currently working with Bootstrap to design responsive columns. My goal is to have the next column of content slide in from either the left or right side when the user clicks on the respective arrow button. While I have found solutions for fixed w ...

Enhancing User Experience with Cascading Dropdown Menus in MVC 5

I've been working on this project for a few days now, trying to get Cascading Dropdownlists to function properly. I'm having an issue where my State dropdownlist is not populating and no error message is displayed when the Ajax call fails. What c ...

The process of toggling a div to slide up and down explained

I'm attempting to create a slide toggle effect on a hidden DIV when a user hovers over specific link buttons. JavaScript: $(function () { // DOM ready shorthand var $content = $(".sliderText"); var $contentdiv = $(".sliderCo ...

Implementing a dynamic top navbar that transitions to the side on desktop with Bootstrap

I have been faced with the challenge of creating a responsive navigation bar that appears at the top on mobile devices and on the side on desktops. The issue arises when considering how to structure the rows and columns to achieve this. For mobile views, ...

Creating a dynamic navbar in an ASP.NET website by populating it with data from a

Seeking guidance on creating a dynamic Bootstrap navbar in an ASP.NET website based on the user's role stored in a database, while maintaining the same style. I have extensively searched for a solution without success. Any assistance would be greatly ...

The Spotify Whitelisted URI may show an error message: { "error": "invalid_grant", "error_description": "Redirect URI is invalid" }

Although there are similar questions out there, I'm facing a different issue. I am trying to obtain an access token from Spotify API, but all I keep getting is the dreaded "invalid redirect uri" error. Below is my API call: const request = require(& ...