通过结构化的Express应用程序提供html和javascript

我目前正在玩Express,并试图解决(我相信应该是)一个微不足道的问题。

我有以下的目录结构:

|-config |---config.js |---routes.js |-server.js |-scripts |---controllers |------controllers.js |---directives |---filters |---services |---templates |---app.js |-views |---index.html 

我的server.js

 var express = require('express'); var app = express(); require('./config/config.js')(app); require('./config/routes.js')(app); app.listen(7777); 

我的config.js

 module.exports = function(app){ app.set('views', __dirname + '../views'); app.engine('html', require('ejs').renderFile); } 

我的routes.js

 module.exports = function(app, express){ app.get('/', function(reg, res){ res.render('index.html') }) app.use(function(err, req, res, next){ console.error(err.stack); res.send(500, 'Something broke!'); }); } 

最后我的index.html

 <html lang="en"> <head> <title></title> <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js'> </script> </head> <body> Hello World!!! </body> </html> 

当我访问本地主机:7000 /

我明白了

 Error: Failed to lookup view "index.html" at Function.app.render (/Users/abe/github/leap-motion-signature-recognition/node_modules/express/lib/application.js:494:17) at ServerResponse.res.render (/Users/abe/github/leap-motion-signature-recognition/node_modules/express/lib/response.js:756:7) at /Users/abe/github/leap-motion-signature-recognition/config/routes.js:7:13 at callbacks (/Users/abe/github/leap-motion-signature-recognition/node_modules/express/lib/router/index.js:161:37) at param (/Users/abe/github/leap-motion-signature-recognition/node_modules/express/lib/router/index.js:135:11) at pass (/Users/abe/github/leap-motion-signature-recognition/node_modules/express/lib/router/index.js:142:5) at Router._dispatch (/Users/abe/github/leap-motion-signature-recognition/node_modules/express/lib/router/index.js:170:5) at Object.router (/Users/abe/github/leap-motion-signature-recognition/node_modules/express/lib/router/index.js:33:10) at next (/Users/abe/github/leap-motion-signature-recognition/node_modules/express/node_modules/connect/lib/proto.js:190:15) at Object.expressInit [as handle] (/Users/abe/github/leap-motion-signature-recognition/node_modules/express/lib/middleware.js:30:5) 

这是为什么? __dirName set不应该挂钩views\index.html

其次,我打算使用这个服务器来支持一个Angular JS应用程序与许多JavaScript文件。 Rails资产pipe道的快速答案是什么? 我怎样才能毫不费力地包含整个目录,没有明确的script标记,并且尽可能地缩短部署时间?

__dirname没有结尾斜杠,所以你应该把__dirname + '../views'改为__dirname + '/../views'

您可以使用静态中间件从目录中提供静态文件:

 app.use(express.static(__dirname + '/scripts')); 

express-uglify可以缩小你的JavaScript文件:

 var expressUglify = require('express-uglify'); app.use(expressUglify.middleware({ src: __dirname + '/scripts' }));