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();
});
}
当然有更好的方法来使用自动为您定位现有文件的模块来提供静态文件。这只是一个简单的回答。
我是一名优秀的程序员,十分优秀!