我对Node.js和JavaScript一般都很陌生,但我想用尽可能少的开销构建一个网站。
我想用Node.js和Bootstrap实现这个目的。
这是我的server.js文件:
var http = require('http');
var fs = require("fs");
http.createServer(
//This function decides which content type to use for wich type of request.
//This is also used to restrict the type of files that a user is allowoed to request.
function(request, response) {
//For debugging
console.log(request.connection.remoteAddress.toString() + " requested the url " + request.url.toString());
if(/^\/[a-zA-Z0-9\/]*.css$/.test(request.url.toString())){
//Send the requested file if it end with .css
sendFileContent(request, response, request.url.toString().substring(1), "text/css");
}
else if(/^\/[a-zA-Z0-9\/]*.js$/.test(request.url.toString())){
//Send the requested file if it end with .js
sendFileContent(request, response, request.url.toString().substring(1), "text/javascript");
}
else {
//Answer any other request with the index.html file, because this is a single page application.
sendFileContent(request, response, "index.html", "text/html");
}
}
).listen(80);
function sendFileContent(request, response, fileName, contentType){
fs.readFile(fileName, function(err, data){
if(err){
response.writeHead(404);
//TODO: Better 404 page!
response.write("Not Found!");
console.log(request.connection.remoteAddress.toString() + " received a 404 error");
}
else{
response.writeHead(200, {'Content-Type': contentType});
response.write(data);
}
response.end();
});
}
效果很好。如果我将脚本添加到html文档中,例如,在其中使用document.write()
,它将显示在页面上。
现在对于Bootstrap,我看到你只需要四个文件,通常是通过CDN或webpack或bower等工具提供的。
所以我刚刚下载了四个文件 bootstrap.min.js,bootstrap.min.css,jquery.min.js 和 popper.js 并将它们放入脚本文件夹旁边的其余文件。当然,我使用相对路径,如scripts/bootstrap/js/bootstrap.min.js
而不是CDN链接。
当运行Node.js服务器时,我可以看到文件被请求并成功发送,但不知道引导外观没有出现(但一切都可见)。
这是我正在使用的HTML文档(index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<title>Index</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="scripts/bootstrap/css/bootstrap.min.css">
</head>
<body>
<div class="alert alert-primary" role="alert">
This is an alert!
</div>
<script type="text/javascript" src="scripts/jquery/jquery.min.js"></script>
<script type="text/javascript" src="scripts/popper/popper.js"></script>
<script type="text/javascript" src="scripts/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
现在,这里有一个奇怪的部分:手动打开index.html文件会导致所有bootstrap元素的正确显示。这就是为什么我认为它与Node.js有关。
有谁知道如何解决这个问题?
答案 0 :(得分:1)
您的正则表达式与您的CSS文件名不匹配,因此它正在提供index.html
而不是实际的CSS。
由于您使用的是.min.css
文件,因此您需要在文件名中查找.
,而不是在扩展名之前:
if(/^\/[a-zA-Z0-9\/.]*.css$/.test(request.url.toString())){
// ^
这同样适用于您的JavaScript。