Problem with Express Server related to MIME type ('text/html') is occuring

Recently, I started learning about Express server module in my school. To practice, I created a simple website but encountered an issue with the CSS file not being executed (checked using Chrome's terminal).

  1. Refused to apply style from 'http://localhost:3000/public/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. home:26
  2. GET http://localhost:3000/public/einstein-home.jpg 404 (Not Found)

const express = require('express');
    const app = express();
    
    app.use(express.static('public')); 
    
    
    app.get('/home', (request, response) => {
        console.log('dirname', __dirname);
        response.sendFile(__dirname + '/views/home.html')
    });
    
    app.get('/about', (request, response) => {
        console.log('dirname', __dirname);
        response.sendFile(__dirname + '/views/about.html')
    });
    
    app.get('/works', (request, response) => {
        console.log('dirname', __dirname);
        response.sendFile(__dirname + '/views/works.html')
    });
    
    
    app.listen(3000, () => {
        console.log('Website about Einstein');
    });
body {
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    background-color: #f2f2f2;
    margin-top: 0px;
    margin-right: 0px;
    margin-bottom: 0px;
    margin-left: 0px;
    font-style: normal;
    font-weight: 200;
}

.container {
    width: 90%;
    margin-left: auto;
    margin-right: auto;
    height: 600px;
    background-color: #FFFFFF;
}

header {
    width: 100%;
    height: 8%;
    background-color: #52bad5;
    border-bottom: 1px solid #2C9AB7;
}

nav {
    float: right;
    width: 50%;
    text-align: right;
    margin-right: 25px;
}
header nav ul {
    list-style: none;
    float: right;
}
nav ul li {
    float: left;
    color: #FFFFFF;
    font-size: 14px;
    text-align: left;
    margin-right: 25px;
    letter-spacing: 2px;
    font-weight: bold;
    transition: all 0.3s linear;
}
ul li a {
    color: #FFFFFF;
    text-decoration: none;
}
ul li:hover a {
    color: #2C9AB7;
}

.text {
    width: 90%;
    text-align: justify;
    font-weight: lighter;
    line-height: 25px;
    float: left;
    padding-left: 20px;
    padding-right: 20px;
    color: #A3A3A3;
}
.about {
    padding-left: 25px;
    padding-right: 25px;
    padding-top: 35px;
    display: inline-block;
    background-color: #FFFFFF;
    margin-top: 0px;
}

.foot {
    text-align: center;
    padding-top: 20px;
    padding-bottom: 20px;
    background-color: #717070;
    color: #FFFFFF;
    text-transform: uppercase;
    font-weight: lighter;
    letter-spacing: 2px;
    border-top-width: 2px;
}


.hidden {
    display: none;
}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" type="text/css" href="public/style.css">
        <script src="http://use.edgefonts.net/source-sans-pro:n2:default.js"></script>  

    </head>
    <body>
<div class="container"> 
  
  <header> <a href="">
    </a>
    <nav>
      <ul>
        <li><a href="#hero">HOME</a></li>
        <li><a href="#about">ABOUT</a></li>
        <li> <a href="#work">WORK</a></li>
      </ul>
    </nav>
  </header>
  <img src="/public/einstein.jpg" width="auto" height="361" alt=""/>
  <section class="about" id="about">
    <h2 class="hidden">About</h2>
    <p class="text">Welcome "Einsteiners". Feel free to find navigate in our website.</p>
</section>

  <footer>
    <article class="footer_column"> </article>
    <article class="footer_column"> </article>
  </footer>

  <div class="foot">e=mc2</div>
</div>
</body>
</html>

If you have any suggestions or feedback regarding this issue, please let me know!

Cheers!

Answer №1

I highly recommend avoiding creating your own templating system: express already includes ejs out of the box, and if you require something more advanced, consider incorporating better templating options like pug or nunjucks. Utilize res.render() to generate your HTML files, instead of using res.write or res.sendFile.

If you are experiencing issues with functionality, make sure to familiarize yourself with how static file serving works in Express: specify which directories Express should check for URL requests before proceeding to actual routes, where the directory names do not directly correspond to the URLs.

For example:

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

If a request is made for yoursite.tld/css/cake.css, it will first search for css/cake.css within public, then within files, before moving on to any matching app.get routes if no path is found in the directories.

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

Create a JavaScript function to calculate a 2-tailed t distribution by adapting an already existing method

Can someone help me with implementing a two-tailed t-test in JavaScript? Resource: Student's t distribution in JavaScript for Google Spreadsheet I have taken a potential solution from the link and customized it to function outside of the form: func ...

Poorly formatted code in VueJS when using Visual Studio Code

After reinstalling Windows and installing Visual Studio Code along with Prettier, I am facing an issue where the formatting is not up to par. Below is an example showcasing the difference between how it looks versus how it should look. Incorrect Formatting ...

Looking to remove an item from an array using Redux?

Is there an issue with my reducers? Here is how they are set up: export default (itemsList = [], action) => { if (action.type === 'ADD_ITEM') { return [...itemsList, action.payload] } return itemList } The deleting reduce ...

Platform for loading websites

Hey guys, so I'm new to website building and I have a question. I need to create a website with multiple menus and pages. In particular, I have a dropdown menu with 5 main menu items, each of which has about six sub-menu items. The content for these s ...

Issue encountered while attempting to start npm: Error code from NPM

I keep encountering the npm ENOENT error every time I attempt to execute npm start. I am unsure of what steps to take in order to resolve this issue. I have made efforts to adjust folder permissions. bryantcaruthers-> npm start npm ERR! code ENOENT npm ...

Customizing style sheets

I need help changing the color of a link to something different from the default hyperlink color. Below is my code snippet: <span class="button"><%= link_to "Create new scenario", :action => "create" %></span> Here's my CSS sect ...

Asynchronous function that delivers results from factory after processing

I am facing an issue with a service(factory) that relies on another service to fetch data. Here is a simplified version of the code: factory('myFactory', function(anotherFactory) { var factoryObject = {}; factoryObject.myMethod = () ...

NextJS 12: The dilemma of styled components not rendering server side due to missing CSS

Exciting news with the latest NextJS 12 release - now styled-components is supported without the need for any extra plugins on NextJS! However, I'm running into issues getting it to work with server-side rendering. To activate it, I installed the sty ...

The process of raycasting with specific points within a collection of points in a Three.js Point

I am facing an issue with my PointCloud object. I want to draw a bounding box around a specific point when clicked, but I can't figure out how to access that individual point within the PointCloud. This is the raycasting code snippet I have been usin ...

Tips for avoiding EADDRINUSE error when conducting database tests with Jest, Graphql, and Sequelize

Trying to test a mock database using Jest and Sequelize, I have created a helper function that runs before each test suite: export function handleTestDatabase() { beforeAll(() => { testDatabase.sequelize.sync().then(() => app.listen(0)); }); ...

Displaying multiple categories of articles on a single page with Node.js

Seeking a solution to limit the number of posts displayed for each category using a .limit() function, but uncertain on how to proceed. Currently utilizing Mongoose and Express in my code setup. The existing code snippet is outlined below: router.get(&a ...

The nodejs events function is being triggered repeatedly

I have been developing a CMS on nodejs which can be found at this link. I have incorporated some event hooks, such as: mpObj.emit('MP:FOOTER', '<center>MPTEST Plugin loaded successfully.</center>'); Whenever I handle this ...

What is the best way to wrap a div in a vertical orientation?

I'm looking to create a vertical div around an image that fluidly changes width: |_________________| | |XXXXXX| | | |XXXXXX| | | |XXXXXX| | | |XXXXXX| | | |XXXXXX| | | |XXXXXX| | |-----------------| The cont ...

Tips for resolving the ExtPay TypeError when using Typscript and Webpack Bundle

I am currently trying to install ExtPay, a payment library for Chrome Extension, from the following link: https://github.com/Glench/ExtPay. I followed the instructions up until step 3 which involved adding ExtPay to background.js. However, I encountered an ...

Experiencing a blank page error when trying to render a partial view using Angular.js

Can someone assist me? I am encountering an issue where the partial view is not rendering properly using ui-router in Angular.js. Below is my code snippet. <!DOCTYPE html> <html lang="en" ng-app="Spesh"> <head> <meta charset="utf- ...

Unexpected Issue with Lightbox2 Functionality in Chrome Browser

Not too long ago, I reached out here for the first time with a similar issue: my image gallery on my art portfolio site was malfunctioning in Chrome, yet worked fine in Microsoft Internet Explorer and Edge. Thanks to some incredibly helpful and patient in ...

Changing the representation of an HTML5 time input to a different format

Can the html5 date input format be converted from one style to another? For instance, changing 2014-06-18 11:17:17 to 18-06-2014 11:17:17 ? ...

Navigating to a new address using ajax and express routing

I am facing an issue with a button having an ID of 'tune-in' on a page named auth.ejs. The button is supposed to navigate to a new page called index.ejs when clicked. However, instead of rendering the index page, clicking the button keeps me on ...

Creating a custom filter

I am working on creating a filter and I could use some assistance with making minimal changes to my code. I am confident that there is a practical solution for what I am trying to achieve and would appreciate any corrections or suggestions. Button01' ...

Calculate the total of an array with the help of the angular forEach function

function dialogController(generate, $scope) { $scope.profiles = generate.get_keys('::role'); $scope.content = {}; $scope.options = []; $scope.servers = {}; $scope.subs = {}; $scope.discountList = {}; $sco ...