【发布时间】:2015-03-23 12:17:49
【问题描述】:
我从 express 为我生成的样板代码开始。我需要dustjs-linkedin 并在app.js 中编译一些简单的模板,如下所示:
var dust = require('dustjs-linkedin');...
app.set('view engine', 'dust');...
var compiled = dust.compile("Hello {name}!","intro");
// add into dust.cache manually
dust.loadSource(compiled);
console.log(dust.cache);
dust.render("intro", {name: "Fred"}, function(err, out) {
if(err){console.log(err)}
console.log(out);
});
这一切都很好,我在终端中看到了 HTML 输出。只有当我开始收到此错误时,我才尝试从路线中执行相同的操作:
GET / 500 11.607 ms - 904
Error: Cannot find module 'dust'
app.get('/', function(req, res){
var compiled = dust.compile("Hello {name}!", "intro");
dust.loadSource(compiled)
dust.render("intro", {name: "Fred"}, function(err, out) {
console.log(out);
res.send(out);
res.close();
});
});
这都在app.js 内,只有它在路由之外起作用,但当我将它移到路由回调中时不起作用。有谁知道为什么它找不到“灰尘”?我需要它,它应该在回调中可见,对吧?
感谢您的帮助!
编辑 1 根据下面的评论,某处需要“灰尘”。我没有在我的代码中这样做;我的猜测是 Express 是在幕后做的,因为我的模板有 '.dust' 文件结尾。我刚刚尝试删除我所有的模板(无论如何都没有使用它们),现在我得到了这个错误:
Error: Failed to lookup view "error" in views directory
我只想看到输出:“Hello Fred”
编辑 2:我想我发现了问题所在
Interrobang 发布的所有内容都是正确的。我认为问题在于 express-generator 为我生成的中间件块:
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
因此,对于每个请求,此中间件都会触发并引发错误。我不是 100% 确定它在做什么,但如果我评论它,一切正常。我现在的第二个问题是,如果我有的话,到底发生了什么?为什么要为所有请求设置它?
【问题讨论】:
-
我正在使用:dustjs-linkedin@2.6.1 和 express@4.12.3
-
该错误并不意味着
dust未定义——这意味着require调用失败。代码中某处有东西在调用require('dust')。 -
我的代码中不需要灰尘,但我在 Express 文档中找到了一些内容:
By default, Express will require() the engine based on the file extension. For example, if you try to render a “foo.jade” file, Express invokes the following internally, and caches the require() on subsequent calls to increase performance. app.engine('jade', require('jade').__express);我的视图确实有一个灰尘文件扩展名,也许 Express 需要灰尘?但是话又说回来……甚至还没有尝试渲染灰尘模板。