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

标签 css node.js

为什么我的 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/

相关文章:

css - 在 css 中,如何在保留另一个类的背景的同时将一个类的背景设置为无?

javascript - Nodejs 哈巴狗扩展

javascript - 将模块包含到另一个nodeJS文件中

node.js - 在 sequelize 中获取 .sum() 中的范围错误?

c# - 仅在父元素可见时启用 RequiredFieldValidator?

javascript - 预加载图像然后将其用作 div 中的背景

javascript - Html/CSS 星级反馈

html - 将对齐的按钮放置在文本框旁边的列内

javascript - 使用 express 启用 http 压缩

javascript - 循环内的 Http 请求