[英]Why is styles.css showing canceled in Developer Tools?
我正在尝试将我的“index.html”文件作为对本地服务器的响应发送,在该 index.html 中,有一个指向外部 CSS 文件的链接。
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", function(req,res){
res.sendFile(__dirname+"/index.html");
});
我已经将链接包含在 HTML head 元素中,如下所示:
<link href="styles.css" rel="stylesheet" >
现在的问题是页面上没有加载“styles.css”文件。 在 Chrome 开发人员工具的网络部分,它显示状态:在“styles.css”前面取消。
为什么会发生这种情况,解决方法是什么? 我尝试了其他人的删除缓存的解决方案,但它不起作用。
编辑: 在这里,我有完全相同的问题,我也尝试过他们的解决方案,但它不起作用
EDIT2 :当我尝试@wilkoklak 的解决方案时,它仍然是同样的错误
您还必须提供 css 文件!
您可以通过使用express.static
来做到这一点
创建一个名为css
的文件夹并将你的styles.css
移动到那里
您的项目结构看起来与此类似
project/
css/
styles.css
server.js
index.js
然后添加这个中间件:
app.use(express.static('css'))
该中间件将查找与css
文件夹中的文件的任何匹配项,并将它们作为响应发送。
当您GET /
(当您打开网页时)时,浏览器还会将GET /styles.css
发送到您的服务器。 您的应用程序中没有/styles.css
路由处理程序。 express.static
为你做这express.static
css无法加载的问题可以通过使用express.static和一个专用的静态文件夹(例如:www)来解决静态文件。
这是使用 express.static 的工作示例:
第一步:将静态文件(index.html、styles.css放在一个名为www的静态文件夹中)
文件夹结构:
/nodejs-web-demo
--> server.js
/www
--> index.html
--> styles.css
第 2 步:在 www(静态)文件夹中创建 index.html 和 styls.css 文件
文件名:www/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/styles.css">
<title>Expressjs website</title>
</head>
<body>
<p class="my-style">Hello! How are you doing?</p>
</body>
</html>
文件名:www/styles.css
.my-style{
color: blue;
}
第 3 步:使用express.static从静态文件夹中提供文件
const http = require('http')
const express = require('express')
const path = require('path')
const app = express()
app.use(express.static("www"))
app.use('/', function(req,res) {
res.sendFile(path.join(__dirname + '/www/index.html'))
})
const server = http.createServer(app)
const port = 3000
server.listen(port)
console.log('Web server started on port # ' + port)
输出:
> node server.js
Web server started on port # 3000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.