如何解决CSS 和 JS 文件未在节点 js 中链接
我想使用中间件 func 来提供静态文件,但问题是我的 css 文件没有使用 node 和 express 与 html 文件链接
错误是:
Refused to apply style from 'http://localhost:4000/static/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type,and strict MIME checking is enabled.
app.js:
const express=require('express');
const path=require('path');
const app=express();
app.use('/public',express.static(path.join(__dirname,'static')));
app.get('/',(req,res)=>{
res.sendFile(path.join(__dirname,'static','index.html'));
});
app.listen(3000);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="/static/css/style.css">
</head>
<body>
<div class="asd">
Hi xyz here..
</div>
<script src="/static/js/script.js"></script>
</body>
</html>
文件夹结构为:
static
css
main.css
js
script.js
index.html
app.js
我尝试了很多,但我无法找到错误, 请帮忙!! 谢谢!!
解决方法
您不需要在路径中添加“/”:
<link rel="stylesheet" type="text/css" href="css/style.css">
此外,您应该在您的应用文件中进行更改:
app.use(express.static(__dirname + '/static'));
这种方式 express 知道它必须从哪里提供静态文件。
,您正在 /public
端点提供静态文件夹。所以你应该把链接改成
<link rel="stylesheet" type="text/css" href="/public/css/style.css">
和
<script src="/public/js/script.js"></script>
还要检查 css 文件的名称。
,我们将不得不做这样的事情:
app.js
const express=require('express');
const path=require('path');
const app=express();
app.use('/public',express.static(path.join(__dirname,'./static')));
app.get('/',(req,res)=>{
res.sendFile(path.join(__dirname,'static','index.html'));
});
app.listen(3000,() => {
console.log("Starting at",3000);
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Document</title>
<script src="/public/js/main.js"></script>
<link rel="stylesheet" href="/public/css/style.css">
</head>
<body>
<div class="asd">
Hi xyz here..
</div>
<script src="/public/js/script.js"></script>
</body>
</html>
截图如下:
我们可以想到的基本拇指规则:
app.use('<something_here>','./static')));
<link rel="stylesheet" href="<something_here>/css/style.css">
<link rel="stylesheet" href="<something_here>/css/style.css">
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。