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

Determining the maximum number within an array using JavaScript

Similar Question: How can I identify the largest number in a JavaScript array? I'm facing issues with this piece of code. Despite spending some time on it, I can't seem to make it work properly. The console only shows 0 when I run it. Can som ...

There was a SyntaxError that caught me by surprise in my Javascript code when it unexpectedly encountered

I have been encountering an error in my code consistently, and I am struggling to comprehend why this is happening. The problematic area seems to be in line 29 of my Javascript file. HTML <link href="Styles12.css"; type="text/css" rel="stylesheet"> ...

Tips for retrieving custom data using NestJS or Express

The middleware indicated that it was passed to the controller after conducting authentication checks. >> Middleware Code async use(req: any, res: any, next: () => void) { const validate = await this.validate(req.cookies.token); const permi ...

Is it possible to access the Express req object inside a Next.js app?

Let's say I have a middleware that includes additional data fields in the express.js req object. My goal is to pass these fields into my React components using my Next.js _app.js. How can I access the req object inside the _app.js file? ...

Invoking a JavaScript function through event emission

I'm trying to figure out how I can trigger a Node/v8 function within Node's main thread using event emitting in a separate C++ thread. Is it feasible to emit events in a C++ thread? Prior to considering NanAsyncWorker or uv_queue_work: My goal i ...

HTML dynamic voting system

I'm new to coding in HTML and I have a specific challenge that I need help with. I want to display a value on my webpage that increases every time a user clicks a button. Below is the code I have written so far: <script type="text/javascript& ...

css content exceeds div boundaries

Hello, I am experiencing an issue with my webpage located at . When I zoom out, the content overflows from its containing div. Setting the height to auto or 100% works fine, but the left column ends up being smaller than the right one, and using clear do ...

The Mongoose getter function is triggering error TS2590 by generating a union type that is too intricate to be displayed

I've come across the TS2590: Expression produces a union type that is too complex to represent error while trying to compile TypeScript. The issue seems to be connected to the id's getter function idFromString, as removing the id getter prevents ...

The value retrieved from the event handler function's state does not match the anticipated value

While debugging, I often minimize this particular component to understand its behavior later on. It was quite challenging to pinpoint the issue due to some intricate logic in place. Nonetheless: import { useContext, useEffect, useState } from "react&q ...

Are there any possible resolutions to the issues plaguing Next.Js?

After switching from React to Next.JS, I've encountered some challenges that I'm hoping to find solutions for: In contrast to React, Next.JS doesn't allow me to change a specific part of a webpage and maintain a static element like a navb ...

Issues arising from the arrangement of the menu bar

I created a navigation bar using an unordered list (ul) with list items (li). However, I encountered an issue where the items were displaying in reverse order until I applied the following CSS: .nav-bar .btn{ float: left; } .nav-bar u ...

Issues encountered when trying to retrieve data from an Express server

I have set up a NodeJS server with Express.js and I am attempting to send a request to it using fetch. fetch("http://localhost:3001/api", { method: "POST", headers: { "Content-Type": "application/json", ...

Preventing reflected XSS attacks in static asset requests in node/express

After conducting a penetration test using the Burp tool on my node(express)/angular application, I discovered a reflected XSS vulnerability. This vulnerability was specifically identified when making a GET request for static assets (no other vulnerabilitie ...

Having trouble with my Bootstrap 4 navbar button - what am I doing wrong?

After conducting research online, I found myself unable to resolve my issue due to my lack of proficiency in English. I apologize for any confusion caused and would like to revisit the topic. The problem lies with my navbar toggle that is not functioning ...

Comparing global variables in ng-switch: Best practices

I'm currently utilizing the AngularJS $rootScope object to expose some global constants that should be accessible to both controllers and views: var app = angular.module('myApp', []); app.run(function ($rootScope) { $rootScope.myConsta ...

Analyze the JSON data retrieved from the API endpoint to determine any

I am currently attempting to utilize axios to send an API request in order to validate login credentials, but I am facing difficulties retrieving the result from the API. The MongoDB .find function successfully locates the correct row, however, I am encoun ...

What causes an error when using a semicolon in an EJS template?

If the semicolon is removed from the following code, the template engine will not throw an error. However, if the semicolon is included, an error will be thrown. <ul> <% for (i = 0; i < array.length; ++i) { %> <%= JSON.stringify( ...

Whenever attempting to generate a new file with nodejs, an error consistently arises

After following the video's instructions to open cmd, type node and press enter, then type touch script.js, I encountered an issue. Instead of creating a js file as expected, I received this error message while using window. Uncaught SyntaxError: Unex ...

What is the best way to dynamically insert an image into an <li> element?

I am looking to enhance my menu by adding an image below each li item as a separator. How can I achieve this using CSS? I want the images to automatically appear whenever a new li tag is added to the ul. Here is the HTML code: <ul class="menu"> ...

Step by step guide on showcasing live server information obtained from the user-end through AJAX technique in a Javascript Pie Chart, within an ASP.NET html template

I have successfully managed to transfer data from the Client Side (C# Back End) to Server Side (JavaScript HTML in aspx) using AJAX. I need help figuring out how to display my own data dynamically in a JavaScript Pie Chart instead of hardcoding values. He ...