2015-03-08 65 views
0

为什么我的css文件只能看似随机加载?我该如何解决这个问题?出于某些原因,我没有使用Express来使用Nodejs。随机地,我的css不会加载我的应用程序

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> 

回答

1

总之,异步是这里的关键。

在您的代码中,只有一个请求处理器,为两个不同的文件调用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),你可以看到这两个请求送达正确。

相关问题