Nodejs Express hbs:css MIMETYPE变成text / html

时间:2018-02-24 07:44:23

标签: node.js express


我知道这个问题之前已被问过很多次但是我已经尝试了所有的解决方案而我仍然无法弄清楚我做错了什么。

我的server.js文件:

  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}`);
});

我的routes.js文件:

module.exports = (app) => {

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

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

manage_accounts.hbs中的我的css链接:

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

请注意,我尝试使用“/plugins/font-awesome/css/font-awesome.min.css”作为href,然后转向http://localhost:3000/accounts/plugins/font-awesome/css/font-awesome.min.css仍然没有工作。

我的文件夹结构:

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

错误:

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.

2 个答案:

答案 0 :(得分:1)

我在文件夹结构中看不到字体真棒css。您的路径不正确或您没有字体副本很棒。这应该是固定的。 要么 您可以使用该文件的CDN版本 https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css

来源:https://cdnjs.com/libraries/font-awesome

答案 1 :(得分:0)

显然问题在于路径。经过一些谷歌搜索后,我找到了解决方案:
我应该使用nodejs中内置的路径模块来设置我的公用文件夹的路径。因为server.js文件不在根目录中,所以路径搞砸了。
新的中间件是这样的:

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