我使用Node.js上的Express框架。我加载的HTML文件没有获取到JavaScript和CSS文件。
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h1>Hello, world!</h1>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script type="" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.js"></script>
</body>
</html>
这是我在Node.js中的express部分:
app.get('/', function(req, res){
console.log(req.path);
fs.readFile('mongo_client/index.html',function (err, data){
if(!err)
{
res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
res.write(data);
res.end();
}
else
{
res.writeHead(400, {'Content-Type': 'text/html'});
res.end("index.html not found");
}
});
});
唯一的 console.log 只打印了“/”。CSS 和 JS 文件甚至都没有被请求。
编辑:
我使用了静态中间件,但它也不起作用。
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
fs.readFile('mongo_client/index.html',function (err, data){
if(!err)
{
res.send(data);;
}
else
{
res.send("index.html not found");
}
});
});
因此,我将我的js和css数据放在public文件夹中。每次尝试连接时,我都会下载index.html文件。有人有使用express的简单Web服务器的工作示例吗?我必须使用文件阅读器吗...我认为还有另一种方法可以使用express中间件。我只需要一个支持css和js的简单express Web服务器的示例...我找不到任何基本内容。
app.use(express.static(__dirname + "/public"));
。 - adeneo