9

I am going to server an static index.html with main.css using this node server:

The serve.js :

var express = require('express')
var cors = require('cors')
var app = express()
var path = require('path');

app.use(cors())

app.use(express.static('assets'))

app.get('/', function (req, res, next) {
  res.sendFile(path.join(__dirname + '/index.html'));
})

app.listen(3000, function () {
  console.log('CORS-enabled web server listening on port 3000')
})

The index.html:

<!doctype html>
<html class="no-js" lang="">
    <head>
        <link rel="stylesheet" type="text/css" href="./assets/css/main.css">

    </head>
    <body>

        <p>Hello Html!</p>
        <div class="thejson"></div>


        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    </body>
</html>

main.css

body {
  background: #ffdd;
  color: #eaeaea;
  padding: 10px;
}

The structure:

project structure:
       index.html
       serve.js
       assets
             js
             css
                main.css

When I load index.html the css is loaded, but serving it fron node, I get:

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

I've also tried href="/assets/css/main.css" and href="./assets/css/main.css" with no avail.

What could be wrong here? How can I fix it?

Babr
  • 1,971
  • 14
  • 33
  • 47

5 Answers5

18

replace this line

app.use(express.static('assets'))

with

app.use('/assets', express.static('assets'))
Codisan
  • 233
  • 3
  • 9
2

I faced the very same problem, and running through the trouble for almost hours, I noticed that I had to use this:

app.use(express.static(__dirname, "../public"));

It should do the job and hopefully, save your time.

Sven Eberth
  • 3,057
  • 12
  • 24
  • 29
Aniket
  • 21
  • 2
0

I've faced the same problem recently. I had index.html in the folder '/public' as well as index.ejs in /views. It'd misled Node.js, so I deleted index.html as well as other html pages from the /public folder. Hopefully, it will save your time

Legion
  • 1
0
app.use('/static', express.static('public'))

use this it will solve your problem.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
0

You have to specify the particular folder you are trying to serve your static files.

app.use('/assets', express.static('assets'))