`Loading CSS files in Node.js with Express``

My CSS isn't loading properly when I run my HTML file. Even though the HTML is correctly linked to the CSS, it seems like express and node.js are not recognizing it. I find it confusing to understand the articles, tutorials, and stack overflow questions related to this issue, so I'm just going to share my code.

I'm also encountering an error message stating that the MIME type is text/HTML, despite verifying multiple times that the MIME type is actually text/CSS.

HTML:

<!DOCTYPE html>
<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>Infinite Road</title>
    <link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
    <div class="infinite">
        <div class="shadow"></div>
    </div>
</body>
</html>

CSS:

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
  body {
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
      background: radial-gradient(#9bdfff, #009be4);
  }
  .infinite {
      position: relative;
      width: 800px;
      height: 160px;
      background: #525252;
      transform-origin: bottom;
      transform-style: preserve-3d;
      transform: perspective(500px) rotateX(30deg);
  }
  .infinite::before {
      content: "";
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      left: 0;
      width: 100%;
      height: 10px;
      background: linear-gradient(90deg, #fff 0%, #fff 70%, #525252 70%, #525252 100%);
      background-size: 120px;
      animation: animate 0.5s linear infinite;
  }
  @keyframes animate {
      0% {
          background-position: 0px;
      }
      100% {
          background-position: -120px;
      }
  }
  .infinite::after {
      content: "";
      position: absolute;
      width: 100%;
      height: 30px;
      background: #333;
      bottom: -30px;
      transform-origin: top;
      transform: perspective(500px) rotateX(-25deg)
  }
  .shadow {
      position: absolute;
      bottom: -93px;
      left: 50%;
      transform: translateX(-50%);
      width: 95%;
      height: 60px;
      background: linear-gradient(#000, transparent);
      opacity: 0.5;
  }

JS:

const path = require('path');
const { readFile } = require('fs');
const app = express();

app.get('/', (request, response) => {
    response.sendFile(path.join(__dirname, "index.html"))
});

app.get('/', (request, responseC) => {
    responseC.sendFile(path.join(__dirname, "style.css"))
});

app.listen(process.env.PORT || 8080, () => console.log('App availible on http://localhost:8080'))

Stackoverflow mentioned that there is a lack of text compared to the amount of code provided, so I decided to include more information.

Answer №1

To set up a folder named "public" in the main directory of your project for serving images, CSS files, and JavaScript files, you can use the following code:

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

Alternatively, you can also use the following code:

const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')));

If everything has been configured correctly, you will be able to access files like this:

http://localhost:3000/css/style.css 

Include the CSS file in your HTML using the following link:

 <link rel="stylesheet" href="/style.css">

Answer №2

Modify

app.get('/', (request, responseC) => {` 

to

app.get('/script.js', (request, responseC) => {

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

Superimpose two actionlinks and prioritize the one appearing above

I have implemented a menu similar to http://tympanus.net/Tutorials/SlideDownBoxMenu/. Below this menu, I have placed a webgrid. The issue I am facing is that when I hover over the menu, the slidedownbox with two action links pops up directly over the heade ...

Is an Ajax powered loading feature used in transitions between pages?

I recently came across this interesting website: It appears that they have implemented a clever technique where new content is dynamically loaded using AJAX, giving the impression of seamless navigation. Additionally, they have succeeded in hiding the bro ...

Working with React Hooks: Implementing a POST request to a server

I am new to React.js and I need help with sending a POST request from a form to a database. I believe I may need to include <form action="URL"> in my implementation. Any assistance would be greatly appreciated. Below is the code snippet fro ...

Locating and updating a sub-document using Mongoose ODM's findOneAndUpdate

I am currently working on a Message schema that includes a sub-document of replies structured like this: message: String, replies: [{ message: String, userFrom: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } }] In m ...

Do all employees (child processes) carry out identical workloads?

Hey there, I'm currently delving into the world of nodejs and finding myself a bit perplexed by the cluster module. To get straight to the point, the Master in this setup creates workers. In my case, I'm working with a 32-bit Windows operating sy ...

Building a loading spinner component in a react-native project

I have successfully implemented a loading spinner that is currently being used in various components of my React project. However, as I am now working on a react-native version of the application, I am faced with the challenge of recreating this loading sp ...

Utilizing Node.js Express to Retrieve AWS S3 Signed URL

My current challenge lies in accessing the AWS S3 signed URL through a Node JS and Express wrapper API that I have developed. To achieve this, I am redirecting a URL to trigger the Node API using nginx. Within the Node API, I am dynamically setting the &a ...

The functionality of saving a file using the jsPDF method is not functioning properly

After dedicating four days to resolving a seemingly straightforward task that involved the jsPDF library, I found myself faced with a challenge. My goal was to save a file using this library, not just print it like I had successfully done before. This is ...

Adjusting font size to perfectly fit within its confines

When using v-for to map out objects from an array into cards, it's important to keep the height consistent throughout the section. Manually adjusting text size with @media queries can be tedious and inelegant, requiring multiple rules for different sc ...

What's the Reason Behind the Ineffectiveness of Footer Background Color in HTML CSS3?

Having some trouble setting the background color for my footer to something other than white. I've been able to successfully change the background of other layout elements, but the footer is giving me issues. Check out the code below: <footer> ...

I noticed that while my shareService is effectively sending values in Angular 2, I encounter an issue where my other components are displaying default values instead

I'm in the process of developing an application using angular 2. I have a UserService that sends a value to other components indicating whether a user is logged in or not, and it's working correctly in terms of data transmission. The issue I&apos ...

I'm having trouble getting my object to display using ng-repeat in Angular. Can anyone help me understand what I'm missing?

My goal was to add an object to an array upon clicking an event, which I successfully achieved. However, the objects are not displaying in the ng-repeat as ordered. Can you help me figure out what's missing? angular.module('app', []); an ...

Console output shows that the function results in undefined

When I pass a string parameter to a function, I expect the console to display "reff", but it is showing "undefined" instead. Here is the code snippet: var _ref; function foo(_ref='reff') { var bar = _ref.bar; return console.log(bar); } foo ...

Exploring the ways to retrieve the returned Dynamic scope in AngularJS

There's a specific need I have - I require a single AngularJS function that can dynamically return the scope variable based on an input parameter. When it comes to controller functions, I've come across examples of how to achieve this dynamic sco ...

What is the best way to format MySQL table data into rows and columns for display?

<?php mysql_connect('server', 'user', 'Pass'); mysql_select_db('add'); $query =mysql_query('select * from addimage'); while( $row = mysql_fetch_assoc($query) ) { echo "$row[url]"; } ?> This code ...

The custom font fails to load on a customized Material UI theme

In my React web application, I tried to implement a custom font by writing the following code: import React, { FunctionComponent } from 'react' import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles' import SofiaPro ...

Unable to resolve the issue within Angular UI modal

Currently, I am facing an issue with displaying a modal using Angular Bootstrap UI. The modal is supposed to resolve items in the controller, but I am struggling to access those resolved items in the modal controller. $scope.showItemsInBill = function(bill ...

Modifications made to the CSS file do not have any impact on React-Slick

Recently, I've been experimenting with altering the appearance of a React-Slick carousel within my GatsbyJS project. Within my Slider component, I followed the official documentation by importing the library as shown below: import Slider from "re ...

The controls for the HTML audio component are missing the download option on Safari

In my React application, I've declared an audio component with controls like the following: <audio controls> <source src={url} /> </audio> While this setup works perfectly in most browsers, it seems to have a bug when used in Safa ...

Creating a personalized script in ReactJS: A step-by-step guide

If I have already built a component with Google Chart in ReactJS, and I want to implement a feature that allows the Legend to show/hide data using a JavaScript script provided here, how and where should I integrate this code to work with my chart? Here is ...