`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

"Learn how event bubbling in jQuery works with the use of .delegate() or .live() methods

After numerous attempts to simplify a code execution, I find myself struggling with loading DOM objects from the server using the .load() function. Specifically, I am encountering issues with implementing a datepicker plugin called jdpicker on an input tex ...

Oops! Looks like there's a problem with the helper called "if_equal" in Handlebars

I attempted to incorporate handlebars into my express node application, but it appears to be malfunctioning. const express = require('express'); const hbs = require('hbs'); const expressHbs = require('express-handlebars'); c ...

How can we transfer data using Routes in React applications?

In my React application, I have a datatable that opens an "Add New" page (a reusable form) when the user clicks on the corresponding button. This AddNew page reads form fields (employeeInputs) specified in App.js. import { employeeInputs } from "./formSour ...

The variable in Vue.js is failing to update, resulting in a "variable is not defined" error

I've been attempting to display the updated value of the totalQuestions variable in the HTML, but I keep encountering the following error. Can someone point out where I went wrong? HTML <label><span class="red-text">Question No: </spa ...

What is the best way to design a content page with linked boxes to various arrays in PHP?

How can I create a PHP menu template that navigates to different pages? I am new to PHP and still learning. I want to achieve something similar to this image: https://i.stack.imgur.com/ylfe8.jpg I have the code for the navigation bar, but I need help crea ...

When executed, the Node application successfully compiles

I have a TypeScript application that runs smoothly in development mode using ts-node. However, after building the application, I encounter some unexpected warnings and errors. This is my tsconfig.json: { "compilerOptions": { "incremen ...

Extracting command line arguments and parameters from a string within a node application for a simulated terminal interface site

In my Next.js project at this source, I have a string called command and I need to extract all the arguments (if any) and parameters (if any) into an array and object, respectively. For example: const command = "login 'username' -p 'secret ...

Navigate to the top of the page prior to updating the Link route in NextJS

Whenever I click on a link to navigate to a new page, the page loads and immediately scrolls to the top. I want to change this behavior so that the scroll resets to the top before the new page is rendered. You can observe this issue on . If you scroll do ...

Having difficulties parsing JSON data in JavaScript

So I've got this script embedded in my HTML code $(document).ready(function() { type :'GET', url :'MapleLeafs2011.json', dataType :'json', success :processTeam, error :function() { alert(&apo ...

What is the best way to create an array within an object during the parsing process

When working with a JSON object, I need to assign a value stored in the session against an ID. The JSON data is as follows: [ { "id": "a", "text": "a", "icon": true, "li_attr": { "id": "a" }, "a_attr": { "href": "#" ...

Modify the class of an input while typing using Jquery

Recently, I created a form using Bootstrap 4. The validation process is done through a PHP file with an AJAX call and it's functioning correctly, except for one issue. I want the input class to switch from "invalid" to "valid" as soon as the user begi ...

Combining Multiple .ts Files into a Single File: A Simplified Application Structure with TypeScript 1.8

Currently, I am in the process of developing an Electron application and I have decided to implement TypeScript for this project. While TypeScript essentially boils down to JavaScript in the end, my familiarity with it makes the transition seamless. As of ...

Leverage JQuery Mobile for smooth sliding and effortless deletion of list elements

Currently, I am testing a JQuery Mobile webpage that features a simple list setup: Upon clicking the list items, they get highlighted and their ids are saved in a local array. Is there an easy (or not so easy) way to transition the selected elements slidi ...

What could be causing TypeScript to throw errors when attempting to utilize refs in React?

Currently, I am utilizing the ref to implement animations on scroll. const foo = () => { if (!ref.current) return; const rect = ref.current.getBoundingClientRect(); setAnimClass( rect.top >= 0 && rect.bottom <= window.i ...

Design a recurring report using an endless JavaScript cycle

I am in the process of creating a brand new scheduled report and have encountered an issue. How can I incorporate a script that includes a loop to run a specific function every 10 seconds? Here's what I have so far: var count = 1; while(count > 0 ...

"Vue is failing to actively update an input that relies on changes from another

I am working on a project where the selected country automatically determines the phone country code. I have set it up so that when I change the country, the corresponding country code should update as well. Within a customer object, both the country and ...

Encountering an unexpected token error while attempting to incorporate JQuery into a React JS project

I am currently diving into the world of React.js and attempting to incorporate a side navigation bar on my homepage. However, I encountered an eslint error when trying to implement the sidebar using jQuery code. Below you will find the code snippet for the ...

Is there a way to add a new button each time a different model is inserted by someone?

My goal is to add a new button each time a new data for a car make is added. However, currently the button keeps getting appended to the same button instead of creating a new one. How can I ensure that a new button is created for each data entry? $.ajax ...

Implement jquery styling to ajax response

Incorporating a jquery carousel to showcase images within a dynamically updated list has proven fruitful initially. However, once the content within the carousel container is replaced via ajax, all formatting seems to vanish. The root cause of this issue ...

A guide on incorporating a JavaScript plugin using Vue.use() into a TypeScript project equipped with typings

Currently, I am facing an issue while attempting to integrate Semantic-UI-Vue into my Vue project. Upon trying to execute Vue.use(SuiVue), the following error message is displayed: Argument of type 'typeof import("semantic-ui-vue")' is not ass ...