gpt4 book ai didi

css - 随机地,我的 css 不会为我的应用程序加载

转载 作者:太空宇宙 更新时间:2023-11-04 12:12:40 24 4
gpt4 key购买 nike

为什么我的 css 文件似乎只是随机加载?我该如何解决这个问题?由于某些原因,我在不使用 Express 的情况下使用 Nodejs。

var http = require('http');
var fs = require('fs');
http.createServer(function (request, response) {
console.log('request starting...');

fs.readFile('./view.html', function(error, content) {
if(error) {
response.writeHead(404);
response.end();
} else {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(content, 'utf-8');
}
});

fs.readFile('./css/appStylesheet.css', function(error, content) {
if(error) {
response.writeHead(404);
response.end();
} else {
response.writeHead(200, {'Content-Type': 'text/css'});
response.end(content, 'utf-8');
}
});

}).listen(3000);
console.log('Server running at localhost on port 3000');

以防万一这部分不是问题所在,下面的代码显示了 html 文件:

<!DOCTYPE html>
<html>
<head>
<title>Sign In</title>
<link rel="stylesheet" type = "text/css" href="/css/appStylesheet.css">
</head>
<body>
<p id = "signIn">
<p>Username</p>
<input type = "text" id = "username" value = "" >
<script>
function username() {
var x = document.createElementById("username").value;
document.getElementById("demo").innerHTML = x;
}
</script>
<p>Password</p>
<input type = "text" id = "password" value = "">
<p><button onclick = "password()">Submit</button></p>
<script>
function password() {
var x = document.createElementById("password").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</p>
</body>
</html>

最佳答案

简而言之,异步是这里的关键。

在您的代码中,只有一个请求处理器,为两个不同的文件调用 fs.readFile 两次。每个调用都有或多或少的类似回调来处理内容。问题是,每个回调都以结束这一行的响应:

response.end(content, 'utf-8');

现在你有一个经典的竞争条件 - 如果第二个 readFile 赢得比赛(即,它首先完成了读取过程),则提供 CSS 文件。如果没有,则提供 HTML 文件。请注意,无论服务器实际查询了哪个文件都没有关系,因为您的回调根本不检查请求!

您(很可能)必须做的是设置请求监听器,以便它检查客户端实际请求的内容 - 并仅提供此文件。一种可能(并且非常简单)的方法:

function serveFile(filePath, fileType, response) {
fs.readFile(filePath, function(err, content) {
if (err) {
response.writeHead(500);
response.end();
}
else {
response.writeHead(200, { 'Content-Type': fileType });
response.end(content, 'utf-8');
}
});
}

var contentTypeFor = {
'/view.html': 'text/html',
'/css/appStylesheet.css': 'text/css'
};

http.createServer(function (request, response) {
if (request.url in contentTypeFor) {
serveFile(request.url, contentTypeFor[request.url], response);
}
else {
response.writeHead(404);
response.end();
}
}).listen(3000);

检查这个(使用 http://localhost:3000/view.html),您会看到两个请求都得到了正确的服务。

关于css - 随机地,我的 css 不会为我的应用程序加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28932611/

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