HTML未正确加载CSS文件。
这是我的html文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<h1>TEST</h1>
</body>
</html>
我的style.css文件与上面显示的.html文件位于同一文件夹中。
这是我的style.css文件:
body {
background: red;
}
当我检查Chrome开发人员工具的“网络”标签时,我的style.css文件被列为“待处理”。
任何想法如何解决这个问题?我尝试禁用AdBlock并清除缓存。
我的服务器在node.js上运行,不确定此处是否相关...
这是我的server.js:
var http = require("http");
// server sends all requests to router file
var router = require("./router.js");
// set the port #
port = "8080";
// server to listen for requests
http.createServer(function (request, response) {
router.home(request, response);
}).listen(port);
// Console will print the message
console.log('Server running at http://127.0.0.1:' + port + '/');
这是我的router.js文件:
var renderer = require("./renderer.js");
var url = require("url");
var htmlHeader = {'Content-Type': 'text/html'};
function home(request, response) {
if (request.url === "/") {
if (request.method.toLowerCase() === "get") {
response.writeHead(200, htmlHeader);
renderer.view("header", {}, response);
renderer.view("footer", {}, response);
response.end();
}
}
}
module.exports.home = home;
最后是renderer.js文件:
// to read contents of [view].html files
var fs = require('fs');
// insert contents into [view].html file
function mergeValues(values, content) {
// cycle over keys
for (var key in values) {
// replace all {{key}} with the value from the values object
content = content.replace("{{" + key + "}}", values[key]);
}
// return merged content
return content;
}
// handle the view passed as an argument
function view(templateName, values, response) {
// find the [view].html file in the /views/ folder
var fileContents = fs.readFileSync('./views/' + templateName + '.html', {encoding: "utf8"});
// insert values in to the content of the view file
fileContents = mergeValues(values, fileContents);
// write out contents to response
response.write(fileContents);
}
module.exports.view = view;
谢谢
最佳答案
与其他HTTP请求一样,由于请求静态文件,服务器将找不到您的CSS文件,因为您没有路由。
您将需要添加以下内容:
if (request.url === "/style.css") {
fs.readFile('style.css', function (err, data) {
response.writeHead(200, {'Content-Type': 'text/css', 'Content-Length': data.length});
response.write(data);
response.end();
});
}
当然,还有更好的方法为静态文件提供模块,该模块可以自动为您找到现有文件。这仅是一个简单的答案。
关于html - HTML无法正确链接到CSS,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35976615/