nodejs表示css和js不加载

我在nodejs上使用express。 我加载的html文件没有得到java脚本和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> 

这是我在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 – 数据放到公共文件夹中。 每次我尝试连接,我下载index.html文件。 有没有人有一个简单的networking服务器使用快递的工作示例? 我是否必须使用文件阅读器…我认为还有另外一种使用express-middleware的方法。

我只需要一个支持css和js的快速web服务器的简单示例…我找不到那些基本的东西。

app.get('/')只会响应根目录中的请求,而不是任何其他的东西。 你的CSS和其他资源在/css/bootstrap.min.css,你的路由不处理。

但是为了expression,请使用static中间件为您做所有这些。 http://expressjs.com/api.html#middleware

本文还解释了设置http://blog.modulus.io/nodejs-and-express-static-content

更新 :一个示例应用程序

Express能够生成支持静态的示例应用程序,并可select支持CSS预处理器。 阅读他们的指南: http : //expressjs.com/guide.html,但基本的步骤是在全球安装快递

 npm install -g express 

然后使用命令行来生成应用程序的框架

 express --css stylus myapp 

以上提供了对Stylus的支持。 如果您愿意,您可以指定较less。 或者用基本的css文件来支持

 express myapp 

然后cd到myapp,或任何你提供的名称,你可以看到它是如何完成的。