gpt4 book ai didi

HTML 没有正确链接到 CSS

转载 作者:太空宇宙 更新时间:2023-11-04 10:38:57 25 4
gpt4 key购买 nike

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 没有正确链接到 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35976615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com