【问题标题】:html view can not load css style because of MIME-type error由于 MIME 类型错误,html 视图无法加载 css 样式
【发布时间】:2019-12-17 03:58:12
【问题描述】:

我创建了一个超级简单的 express 应用程序,它将显示来自视图目录的一个 home.html 视图。一切正常home.html 已显示,但我没有添加任何 CSS 样式。在控制台中我只收到一个错误:

我试图从堆栈中找到另一个答案来解决我的问题,例如:

  • 更改 app.use()
    • 来自 -> app.use(express.static(path.join(__dirname, 'public')))
    • 到 -> app.use(express.static(path.join(__dirname + '/public')))

好的,你可以看到我的目录结构是什么样子的

如您所见,我创建了公用文件夹,并在此文件夹中保留了我的 css 样式,所以在 url 下:http://localhost:8080/public/css/style.css 我应该看到我的 css 样式,但我只能看到错误

但同时在这个 url http://localhost:8080/css/style.css 下我可以找到我的 css 文件

我真的很困惑,我不知道我做错了什么。如果有人帮助我,我会很高兴。

  • app.js

    const express = require('express');
    const path = require('path');
    const bodyParser = require('body-parser');
    const cookieParser = require('cookie-parser');
    const flash = require('connect-flash');
    const routes = require('./routes/index');
    const app = express();
    
    app.set('views', path.join(__dirname, 'views'));
    app.engine('html', require('ejs').renderFile);
    app.set('view engine', 'html');
    
    app.use(express.static(path.join(__dirname, 'public')));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(cookieParser());
    app.use(flash());
    app.use('/', routes);
    
    module.exports = app;
    
  • server.js

    const app = require('./app');
    
    app.set('port', process.env.PORT || 8080);
    
    const server = app.listen(app.get('port'), () => {
        console.log(`Server is up on ${server.address().port}`);
    });
    
    
  • home.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="/public/css/style.css">
        <title>Express</title>
    </head>
    <body>
        <h1>Express</h1>
    </body>
    </html>
    
  • style.css

    body {
        background: #f6f6f6;
    }
    h1 {
        color: green;
    }
    

【问题讨论】:

  • 因为你发送的 css 是 mimetype text/html 它应该是 text/css
  • &lt;link&gt; 在 home.html 中的什么位置?我添加:&lt;link rel="stylesheet" type="text/css" href="/public/css/style.css"&gt; 所以类型是text/css。或者你的意思是另一个地方?
  • 从服务器端它应该是text/css mimetype。在您的 html 中,无需添加 type 属性。
  • 。它必须工作。 express.static 使您的公用文件夹等于localhost:3000。这将直接映射到公用文件夹。您无需再次公开。
  • 是的@AmaranadhMeda 是的,你是对的,谢谢:D

标签: javascript node.js express


【解决方案1】:

好的,所以我在快速服务器配置方面犯了错误。而不是像

那样提供静态文件
  • app.use(express.static(path.join(__dirname, 'public')));

  • app.use('/public', express.static(path.join(__dirname, 'public')));

这是因为 /public 目录是在根 url 下提供的

【讨论】:

    猜你喜欢
    • 2021-04-03
    • 2021-04-18
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    相关资源
    最近更新 更多