我正在尝试使用 node.js 设置客户端/服务器程序。 我有以下代码,它在连接时返回一个 .html 文件。
JavaScript:
var http = require('http');
const fs = require('fs');
var server;
fs.readFile('./FrontPage.html', function (err, html){
if (err){
throw err;
}
server = http.createServer(function (req, res) {
res.writeHead(200, {
"Content-Type": "text/html"
});
res.write(html);
res.end();
console.log("HTTP response sent");
});
var port = 3000;
server.listen(port, function () {
console.log("Server listening on port " + port);
});
});
HTML:
<head>
<link rel="stylesheet" type="text/css" href="./css/FrontPageCSS.css">
</head>
<body style="background-image:url(./img/bg.jpg)">
<div id="header">
<a href="./frontPage.html"><img src="./img/Logo.png" height="5%" width="5%" alt="logo"></a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="./script/FrontPageJS.js"></script>
</div>
<div id="buttonWrapper">
<div id="first" class="first">
This is my first button
</div>
<div id="second" class="second">
This is my second button
</div>
</div>
当我在浏览器中访问端口 3000 上的 localhost 时,它返回没有 CSS 的 .html 文件。当我通过它的路径单独打开 .html 时,CSS 工作正常。
我的问题:为什么 CSS 没有包含在响应中,我该如何包含它?
最佳答案
CSS 文件不包含在 HTML 中。 它们在 HTML 解析期间由浏览器下载。
您的示例不起作用,因为当浏览器尝试获取 css/FrontPageCSS.css 时,它会获取 HTML 输出,因为您的服务器始终响应 FrontPage.html 文件的内容。
我建议你使用一些 web 框架作为 express:http://expressjs.com/en/index.html
关于html - Node.js 不会发送 CSS 作为响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34071030/