2

我目前正在玩 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);
}

我的路线.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>

当我访问 localhost: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吗?

其次,我打算使用这个服务器来支持一个带有许多 javascript 文件的 Angular JS 应用程序。Rails 资产管道的 Express 答案是什么?如何在没有明确script标记的情况下轻松地包含整个目录,并且如果可能的话,还可以缩短部署时间?

4

1 回答 1

2

__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' }));
于 2013-08-06T09:20:50.220 回答