node.js - ExpressJS 在静态目录中查找 View ,忽略 View 目录

标签 node.js express cloud9-ide

根据 ExpressJS application settings documentation ,您应该能够将 views 设置为 View 引擎的目录。我遇到了我认为可能是错误的情况; Express 不是在 views 目录中查找,而是在 static 目录中查找。显然它失败了,因为它不存在。我通过将 View 移动到静态目录中确认了这一点,并且错误消失了。

您可以通过克隆 this Cloud9 project 来查看此错误。我无法在 Cloud9 之外确认此错误(我没有可用的 Linux 盒子)。

目录结构简单

项目

|-client
  |-assets
  |-views
    |-index.html
|-server.js

这是服务器配置

var viewDir = __dirname + '/client/views/';
var assetDir = __dirname + '/client/assets/';

//Configure
app.configure(function() {
    app.set('views', viewDir);
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express['static'](assetDir));
    app.use(app.router);
});

app.get('/', function(req, res){        
    res.render('index');
});

最佳答案

您需要通过设置引擎来告诉它如何渲染。

例如回声:

app.engine('.html', function (file, options, next) {
  fs.readFile(file, function (err, data) {
    if (err) {
      next(err);
    } else {
      next(null, data.toString());
    }
  });
});

如果您希望它占据主导地位,您还需要将 app.get('/' . . .) 放在 app.use(express.static 之前。

您可以在这里尝试一下:http://runnable.com/UWTRSNJq0z5OAADk

关于node.js - ExpressJS 在静态目录中查找 View ,忽略 View 目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15912085/

相关文章:

node.js - 将 pdf url 传递给查询字符串中的 pdf.js

c++ - 未在 Windows 8.1 上构建的 Node 包 - 缺少 Microsoft.Cpp.Default.props

javascript - Electron 构建应用程序无法启动 Express 服务器

node.js - 如何访问 express.js 中的 ejs 对象

node.js - 无法从 Cloud9 IDE 将 Node.js 部署到 Azure 网站

node.js - 防止 NodeJS 程序退出

sql - 使用 sequelize node.js 执行查询时分组格式错误

node.js - 将用户保存到 MongoDB 的 Passport Facebook 策略

sails.js - 在 cloud-9 ide 中运行 Sails js

ruby-on-rails - 如何在 Cloud9 IDE 开发服务器中处理 Twilio 回发?