node.js - 你如何使用 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;
}
解决方案
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'));
推荐阅读
- sql-server - 如何处理sql表中的空值
- c - 使用 I/O 多路复用时的非阻塞套接字
- c# - Identity Server + Azure Active Directory + Blazor 角色声明问题
- solr - 我可以在 Solr 查询中查询 2 个不同的集合吗?
- vuejs3 - Vue 3 中的自定义指令
- powerbi - Power BI:填补两个日期之间的空白,排除超出范围的日期
- github - GitHub 检查更改它在 Azure DevOps 中构建的存储库
- openstack - 从先前的命令输出重新创建 openstack 工件?
- r - 如何标记散点图上对角线以下的所有点
- pandas - 获取 TypeError:稀疏矩阵长度不明确;在进行多类分类时使用 getnnz() 或 shape[0]