首页 > 解决方案 > 你如何使用 express 服务 css 文件?

问题描述

我已经看到了很多类似的问题,但我所做的似乎没有任何效果。未提供 css 文件。我不断收到以下错误。

拒绝应用来自 ' http://localhost:7000/public/css/styles.css ' 的样式,因为它的 MIME 类型 ('text/html') 不是受支持的样式表 MIME 类型,并且启用了严格的 MIME 检查。

launch-analytics.js:4 Uncaught TypeError: Cannot read property 'parentNode' of undefined at launch-analytics.js:4 at launch-analytics.js:5 (anonymous) @ launch-analytics.js:4 (anonymous) @ launch -analytics.js:5

我的 index.ejs 文件(路径:user/Node/views/index.ejs)

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <link rel="stylesheet" href="public/css/styles.css" type="text/css">
    <body>
        <p>I am the home page</p>
    </body>
</html>

app.js 文件:(路径:用户/节点)

let express = require('express');
let bodyParser = require('body-parser');

let app = express();

let urlencodedParser = bodyParser.urlencoded({ extended: false })


app.set('view engine', 'ejs');

app.use(express.static('/public'));

app.get('/', function(req,res){
    res.render('index');
});

app.listen(7000);

样式.css 文件:

body{
    background-color: skyblue;
    font-family: verdana;
    color: white;
    padding: 30px;
}
h2{
    font-size: 49px;
    text-transform: uppercase;
    letter-spacing:2px;
    text-align: center;
}
p{
    font-size: 16px;
    text-align: center;
}
.text-field{
    display: flex;
    justify-content: center;
}

标签: node.jsexpress

解决方案


It looks like app.use(express.static('/public')); is pointing to directory relative to root dir. Change it to app.use(express.static(__dirname + '/public'));


推荐阅读