The CSS in Node.js stubbornly refused to be implemented

I'm in the process of creating a straightforward application, and while setting up the project, I encountered an issue. I have a basic localhost server and an HTML file to display, but upon accessing the localhost, I received this error in the console:

Refused to apply style from 'http://localhost:8080/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

I came across this answer but couldn't grasp the problem, hence, couldn't resolve mine.

The project structure looks like this:

Project
  js
    server.js
  views
    index.html
    style.css

Here is the code contained in the files:

server.js:

const express = require('express');
const dotenv = require('dotenv');
const path = require('path');

dotenv.config({ path: './../config.env' });
const app = express();

app.use(express.static(__dirname + '/views'));

const port = process.env.PORT || 8080;
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '../views', 'index.html'));
});

app.listen(port, () => {
  console.log(`App running on port ${port}`);
});

index.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>Document</title>
    <link rel="stylesheet" type="text/css" href="/style.css" />
  </head>
  <body>
    <button class="btn"></button>
  </body>
</html>

style.css:

.btn {
  background-color: red;
}

Expected the button to have a red background color, but faced the mentioned error instead. Any assistance would be highly appreciated!

Answer №1

The issue you encountered was related to the path you provided for static.

Instead of

app.use(express.static(__dirname + '/views'));
, consider using __dirname as the path for your js file. This means you should go up one directory and then access the views folder.

To achieve this, you can utilize the same method used in your get('/'... by using path.join to access your views directory.

For example:

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

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

Struggling to display Firebase Auth information resulting in 'undefined' value within React web application

When loading a user's profile page, I am trying to display their displayName and email information retrieved from Firebase Auth. I have implemented this logic within the 'componentDidMount' method by updating the state with the response dat ...

Creating a 3-column div with varying sizes of text in another div at the center position

I am attempting to create a 3-column layout using only DIVs, but I am facing some challenges. If I were to use tables in the traditional HTML 4 way, I could achieve this: <div style="width:100%"> <table width="50%" align="center"> ...

Encountering a NextJS error with head component

Trying to incorporate the head element into a NextJS page format has proven challenging. Despite consulting the official documentation, implementing next/head to add <head> has resulted in an error within the code block. Code: import Head from &apos ...

Adjust background image size to fit the dimensions of the foreground content

I have a div where an image and content are inside. I am trying to make the background image adjust its size based on the content within it, rather than showing the full image size with empty space. My current styling uses flexbox: .section { height: ...

What is the best way to transfer a variable from the backend to the front end and showcase it on the console?

Is there a way to transfer JSON data from a NodeJS variable to the AngularJS side without having to store it in a database first? I need to display this data on the Angular console. Any suggestions on how to achieve this? ...

Exploring ways to access global window variables in React using JavaScript

I've been following the discussion on how to transfer variables from JavaScript to ReactJS. Here is my array of objects in JavaScript: window.dataArr = []; function makeJsObj(descr, currDate, done) { var data = {}; console.log(descr ...

iPhone users may encounter a freezing issue with the footer when scrolling

Can someone assist in keeping the footer at the bottom right of the screen on my website? When I view it on my iPhone, the footer remains fixed when scrolling down. Here is how it looks: . Your help would be greatly appreciated. Thank you and have a wonder ...

Tips for separating these two words onto two separate lines

I created this box using Angular Material, but I am having trouble breaking the words "1349" and "New Feedback" into two lines. Here's an image included in my design. Any tips on accomplishing this in Angular Material? Thank you! <style> . ...

Secondary Form Checkbox Input

Presently, I am working with a dynamic form-checkbox input element. <b-form-group label="Skills"> <b-form-checkbox-group v-model="form.selected" :options="options"/> </b-form-group> However, I am looking to enhance this functionalit ...

Why does my CSS attribute selector fail to update when the property's value changes?

Context: I'm working on a React-based web app that utilizes traditional CSS loaded through an import statement. In order to create a slider functionality, I have applied a CSS selector on the tab index attribute. Challenge: The issue I am facing is t ...

Hide the 1, 2, 3 page buttons in Datatables pagination and instead display only the Next and Previous buttons for navigation

I recently implemented datadables.net pagination for my HTML table. I am looking to customize the pagination buttons by hiding or removing the 1, 2, 3 ... buttons and only display Next and Previous Buttons. Is there a way to achieve this by setting paging ...

Align the content evenly on several cards using Material-UI

Trying to work on some frontend coding, but struggling with getting the content justified properly in fixed-height MUI cards. Each card consists of a title, description, divider, and author, but I can't seem to get everything aligned correctly within ...

How to Perform a Method Call or Array Iteration in JSX within HTML

Encountering a new issue that I haven't faced before, this is my first time working on something like this and finding a solution is proving to be tricky. Currently, I'm using SendGrid to send an HTML email through a POST request in express on N ...

Notification pop-up for accepting cookies on a website

I am curious about how to insert a .js code into a button within a bootstrap alert so that when the user clicks 'accept', the alert box does not reappear. Thank you very much. Here is the code I have, but it is not working. Javascript: $(".bt ...

Clever method for enabling image uploads upon image selection without needing to click an upload button using JQuery

Is there a way to automatically upload the file without having to click the upload button? Detail : The code below shows an input field for uploading an image, where you have to select the file and then click the "Upload" button to actually upload it: & ...

Changing the color of MUI Typography when selected

Struggling to modify the styling of the Typography component nested inside a MenuItem. Unable to apply styles to ListItem as intended Check out my code here: https://codesandbox.io/s/dztbc?file=/demo.tsx:1481-1804 Desired behavior: Change styling on sele ...

The event is not triggered by ng-submit

I'm struggling with submitting this form. I've checked everything, but it just won't work. This is my HTML: <html ng-app = 'myApp'> <div ng-controller="Tabs"> ... <form ng-submit="sendClicked()" &g ...

Ways to address the dependencies problems when using npm install @types/react?

Encountering an issue with the @types/react package. This pertains to a small UI project developed on top of the nextron platform. Everything was functioning smoothly until I had to reinstall my Windows OS. Attempting to rebuild the project using yarn an ...

The jQuery code stops functioning once the identical HTML content is loaded through AJAX

Before you mark my question as a duplicate, I have already attempted the solutions provided by similar issues, but unfortunately none of them have resolved my problem. Here is my specific issue: I am working with a fragment that includes the following inpu ...

Guide to activating the 'Next' button on WP Forms using JavaScript code when certain conditions are fulfilled

Is there a way to adjust the JavaScript code provided so that the visibility of the "Next" button is dependent on whether at least one item in the 'wpforms-icon-choices-item' class has the '.wpform-selected' class on the current page or ...