【发布时间】:2014-04-10 19:46:31
【问题描述】:
我在 nodejs 上使用 express。我加载的 html 文件没有得到 java-scripts 和 css-files。
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>
这是我在 nodejs 中的表达部分:
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 的简单网络服务器的工作示例?我是否必须使用文件阅读器...我认为还有另一种使用 express-middleware 的方法。
我只需要一个支持 css 和 js 的快速网络服务器的简单示例......我找不到任何基本的东西。
【问题讨论】:
-
使用 express 你不需要 res.writeHead、res.write、res.end。只需做 res.send(data)。而在 err 情况下,只需用 console.log(err) 打印 err 看看读取文件是否有问题。
-
你是说它甚至没有从 CDN 获取 jQuery,或者只是本地文件。你有静态文件的静态路由吗?
-
jQuery 正在加载。我没有静态路由。如果我 res.send(data) 我下载该网站。
-
然后添加一个静态路由,比如
app.use(express.static(__dirname + "/public"));