Soli
Soli

Reputation: 882

Nodejs Express hbs: css MIMETYPE turns into text/html


I know this question has been asked many times before but I have tried all the solutions and I still can't figure out what I'm doing wrong.

My server.js file:

  const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const routes = require('./routes.js');
const hbs = require('hbs');


let app = express();
const port = process.env.PORT || 3000;

app.use(express.static(__dirname + '/public'));
app.set('view engine', 'hbs');
app.use(bodyParser.json());
app.use(morgan('dev'));

routes(app);

app.listen(port, () => {
    console.log(`Started up at port ${port}`);
});

My routes.js file:

module.exports = (app) => {

    app.get('/', (req, res) => {
        res.send('Hello World!');
    });

    app.get('/accounts', (req, res) => {        
       res.render('manage_accounts.hbs');
    });
};

My css link in manage_accounts.hbs:

<link rel="stylesheet" type="text/css" href="/public/plugins/font-awesome/css/font-awesome.min.css" />

Note that I have tries using "/plugins/font-awesome/css/font-awesome.min.css" as href and it turns to "http://localhost:3000/accounts/plugins/font-awesome/css/font-awesome.min.css" which still doesn't work.

My folder structure:

/project
  /server
    server.js
    routes.js
  /views
    manage_accounts.js
  /public
    plugins/
       plugin/
          plugin.css

Error:

Refused to apply style from 'http://localhost:3000/public/plugins/font-awesome/css/font-awesome.min.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

Upvotes: 2

Views: 1465

Answers (2)

Soli
Soli

Reputation: 882

So apparently the problem was with path. After some googling I found out the solution:
I should use path module which is built-in in nodejs in order to set the path of my public folder. Because the server.js file is not on the root directory and so the path gets messed up.
The new middleware is something like this:

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

Upvotes: 0

theAnubhav
theAnubhav

Reputation: 533

I couldn't see font awesome css in your folder structure. Either you path is incorrect or you don't have copy of font-awesome. This should be fixed. OR You can use CDN version of the file, something like https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css

source: https://cdnjs.com/libraries/font-awesome

Upvotes: 1

Related Questions