错误: 没有指定默认引擎,也没有提供扩展

我正在使用 node.js 和 engine 设置一个 http 服务器。然而,我一直遇到的问题,我没有什么信息,如何解决我会感激一些帮助解决这个请。

Error: No default engine was specified and no extension was provided.
at new View (...\node_modules\express\lib\view.js:41:42)
at Function.app.render (...\node_modules\express\lib\application.js:484:12)
at ServerResponse.res.render (...\node_modules\express\lib\response.js:783:7)
at Layer.handle (...\app.js:123:7)
at trim_prefix (...\node_modules\express\lib\router\index.js:225:17)
at c (...\node_modules\express\lib\router\index.js:198:9)
at Function.proto.process_params (...\node_modules\express\lib\router\index.js:253:12)
at next (...\node_modules\express\lib\router\index.js:189:19)
at next (...\node_modules\express\lib\router\index.js:202:7)
at next (...\node_modules\express\lib\router\index.js:166:38)

下面是我已经设置启动这个引擎。

var http = require('http');
var module = require("module")
var logger = require('morgan');
var express = require('express');
var app =  module.exports = express();
var silent = 'test' == process.env.NODE_ENV;
var httpServer = http.createServer(app);  // app middleware


app.enable('strict routing');
// app.all('*', function(req, res, next)/*** CORS support.*/
// {
//   if (!req.get('Origin')) return next();// use "*" here to accept any origin
//   res.set('Access-Control-Allow-Origin', 'http://localhost:3000');
//   res.set('Access-Control-Allow-Methods', 'GET, POST');
//   res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
//   res.set('Access-Control-Allow-Max-Age', 3600);
//   if ('OPTIONS' == req.method) return res.send(200);
//   next();
// });
app.set('views', __dirname + '/views'); // general config
app.set('view engine', 'html');
app.get('/404', function(req, res, next){
next();// trigger a 404 since no other middleware will match /404 after this one, and we're not responding here
});
app.get('/403', function(req, res, next){// trigger a 403 error
var err = new Error('not allowed!');
err.status = 403;
next(err);
});
app.get('/500', function(req, res, next){// trigger a generic (500) error
next(new Error('keyboard cat!'));
});
app.use(express.static(__dirname + '/public'));
//error handlers
app.use(logErrors);
app.use(clientErrorHandler);
app.use(errorHandler);
// middleware with an arity of 4 are considered error handling middleware. When you next(err)
// it will be passed through the defined middleware in order, but ONLY those with an arity of 4, ignoring regular middleware.
function clientErrorHandler(err, req, res, next) {
if (req.xhr) {// whatever you want here, feel free to populate properties on `err` to treat it differently in here.
res.send(err.status || 500, { error: err.message });
}
else
{ next(err);}
};
// create an error with .status. we can then use the property in our custom error handler (Connect repects this prop as well)
function error  (status, msg) {
var err = new Error(msg);
err.status = status;
return err;
};
function logErrors  (err, req, res, next) {
console.error(err.stack);
next(err);
};
function errorHandler (err, req, res, next) {
res.status(500);
res.render('error', { error: err });
};


// Error handlers
// Since this is the last non-error-handling middleware use()d, we assume 404, as nothing else responded.
// $ curl http://localhost:3000/notfound
// $ curl http://localhost:3000/notfound -H "Accept: application/json"
// $ curl http://localhost:3000/notfound -H "Accept: text/plain"
app.use(function(req, res, next){
res.status(404);
if (req.accepts('html')) {// respond with html page
res.render('404', { url: req.url });
return;
}
if (req.accepts('json')) {// respond with json
res.send({ error: 'Not found' });
return;
}
res.type('txt').send('Not found');// default to plain-text. send()
});


// error-handling middleware, take the same form as regular middleware, however they require an
// arity of 4, aka the signature (err, req, res, next).when connect has an error, it will invoke ONLY error-handling middleware.


// If we were to next() here any remaining non-error-handling middleware would then be executed, or if we next(err) to
// continue passing the error, only error-handling middleware would remain being executed, however here
// we simply respond with an error page.
app.use(function(err, req, res, next){
// we may use properties of the error object here and next(err) appropriately, or if we possibly recovered from the error, simply next().
res.status(err.status || 500);
res.render('500', { error: err });
});


if (!module.parent) {// assigning to exports will not modify module, must use module.exports
app.listen(3000);
silent || console.log('Express started on port 3000');
};
340882 次浏览

您缺少视图引擎,例如使用 翡翠:

改变你的

app.set('view engine', 'html');

app.set('view engine', 'jade');

如果希望使用 HTML 友好的语法,请使用 Ejs

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

剪辑

正如您可以从 View.js Express 视图模块中读到的

module.exports = View;


/**
* Initialize a new `View` with the given `name`.
*
* Options:
*
*   - `defaultEngine` the default template engine name
*   - `engines` template engine require() cache
*   - `root` root path for view lookup
*
* @param {String} name
* @param {Object} options
* @api private
*/


function View(name, options) {
options = options || {};
this.name = name;
this.root = options.root;
var engines = options.engines;
this.defaultEngine = options.defaultEngine;
var ext = this.ext = extname(name);
if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no extension was provided.');
if (!ext) name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') + this.defaultEngine);
this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express);
this.path = this.lookup(name);
}

你一定安装了 default engine

Expressprogram.template搜索默认布局视图,如下所示:

mkdir(path + '/views', function(){
switch (program.template) {
case 'ejs':
write(path + '/views/index.ejs', ejsIndex);
break;
case 'jade':
write(path + '/views/layout.jade', jadeLayout);
write(path + '/views/index.jade', jadeIndex);
break;
case 'jshtml':
write(path + '/views/layout.jshtml', jshtmlLayout);
write(path + '/views/index.jshtml', jshtmlIndex);
break;
case 'hjs':
write(path + '/views/index.hjs', hoganIndex);
break;


}
});

如下所示:

program.template = 'jade';
if (program.ejs) program.template = 'ejs';
if (program.jshtml) program.template = 'jshtml';
if (program.hogan) program.template = 'hjs';

默认的视图引擎是 jade

注释掉代码中的 res.render行,改为添加 next(err);。如果您没有使用视图引擎,res.render会抛出一个错误。

对不起,你必须把这一行也注释掉:

app.set('view engine', 'html');

但是,我的解决方案将导致不使用视图引擎。你不需要一个视图引擎,但是如果这是你的目标,试试这个:

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//swap jade for ejs etc

在使用视图引擎时,你也需要 res.render行:

// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
next(err);
res.render('error', {
message: err.message,
error: {}
});
});

我刚刚收到这个错误消息,问题是我没有正确地设置我的中间件。

我正在构建一个博客的 刻薄堆栈和需要的 。玉文件的正文解析,我在前端使用。下面是我的“ /中间件/index.js”文件中的代码片段,来自我的项目。

var express = require('express');
var morgan = require('morgan');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');


module.exports = function (app) {
app.use(morgan('dev'));


// Good for now
// In the future, use connect-mongo or similar
// for persistant sessions
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(session({secret: 'building a blog', saveUninitialized: true, resave: true}));

此外,这里是我的“ 包裹 Json”文件,您可能使用不同版本的技术。 注意: 因为我不确定它们之间的依赖关系,我在这里包含了整个文件:

"dependencies": {
"body-parser": "1.12.3",
"consolidate": "0.12.1",
"cookie-parser": "1.3.4",
"crypto": "0.0.3",
"debug": "2.1.1",
"express": "4.12.2",
"express-mongoose": "0.1.0",
"express-session": "1.11.1",
"jade": "1.9.2",
"method-override": "2.3.2",
"mongodb": "2.0.28",
"mongoose": "4.0.2",
"morgan": "1.5.1",
"request": "2.55.0",
"serve-favicon": "2.2.0",
"swig": "1.4.2"
}

希望这对谁有帮助! 一切顺利!

上面的答案是正确的,但是我发现一个简单的输入错误也会产生这个错误。例如,我用 var router = Express ()代替 var router = Express。路由器()得到这个错误。所以应该是这样的:

// App.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended:false}));
// assuming you put views folder in the same directory as app.js
app.set('views', __dirname + '/views')
app.engine('ejs', ejs.renderFile);
app.set('view engine', 'ejs');
// router - wherever you put it, could be in app.js
var router = express.Router();
router.get('/', function (req,res) {
res.render('/index.ejs');
})

如果您没有使用视图引擎,那么 res.render 内容将抛出一个错误。

如果您只想为 json 服务,请将代码中的 res.render('error', { error: err });行替换为:

res.json({ error: err })

PS: 人们通常在返回的对象中也有信息:

res.status(err.status || 500);
res.json({
message: err.message,
error: err
});

如果您希望呈现 html 文件,请使用:

response.sendfile('index.html');

然后你去掉:

app.set('view engine', 'html');

*.html放在 views目录中,或者将 public目录作为静态目录提供服务,并将 index.html放在 public目录中。

如果所需要的只是在代码中内联发送 html 代码,我们可以使用下面的代码

var app = express();
app.get('/test.html', function (req, res) {
res.header('Content-Type', 'text/html').send("<html>my html code</html>");
});

您可以使用 Express-error-handle 来使用静态 html 页面进行错误处理,并避免定义视图处理程序。

这个错误可能是由一个404引起的,也可能是一个缺少的图标(如果您包含了前面的控制台消息,那么就很明显了)。“ html”的“视图处理程序”在4.x Express 中似乎无效。

不管原因如何,只要修改配置的其他元素,就可以避免定义(有效的)视图处理程序。

解决这个问题的选择是:

  • 与其他答案一样定义有效的视图处理程序
  • 使用 send ()代替 render 直接返回内容

Http://expressjs.com/en/api.html#res.render

使用不带文件路径的呈现会自动调用视图处理程序,如配置中的以下两行所示:

res.render('404', { url: req.url });

以及:

res.render('500);

确保使用以下命令安装 Express-error-handle:

npm install --save express-error-handler

然后将其导入到应用程序中

var ErrorHandler = require('express-error-handler');

然后将错误处理更改为:

// define below all other routes
var errorHandler = ErrorHandler({
static: {
'404': 'error.html' // put this file in your Public folder
'500': 'error.html' // ditto
});


// any unresolved requests will 404
app.use(function(req,res,next) {
var err = new Error('Not Found');
err.status(404);
next(err);
}


app.use(errorHandler);

设置视图引擎跟踪方式

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

只需在代码中设置视图引擎。

var app = express();
app.set('view engine', 'ejs');

错误: 没有指定默认引擎,也没有提供扩展

我也遇到了同样的问题(因为做了一个平均堆栈项目)。.问题是我没有提到安装 npm 的格式,即: pug 或 Jade,ejs 等,所以要解决这个 goto npm 并输入 Express —— view = pug foldername。这将加载必要的 pug 文件(index.pug、 layout.pug 等)在你给定的文件夹里。

如果你通过使用快速生成器得到了这个错误,我已经通过使用

express --view=ejs myapp

而不是

express --view=pug myapp

请更换

app.set('view engine', 'html');

app.set('view engine', 'ejs');

而不是

app.get('/', (req, res) => res.render('Hellooooo'))

使用

app.get('/', (req, res) => res.send('Hellooooo'))

如果您正在使用 NestJS,那么为了解决这个问题,您必须更改 main.ts 文件。 请考虑使用下面的例子:

就像 NestJS-MVC里的这个演示

import { NestFactory } from '@nestjs/core';
import { NestFastifyApplication, FastifyAdapter } from '@nestjs/platform-fastify';
import { AppModule } from './app.module';
import { join } from 'path';


async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(),
);
app.useStaticAssets({
root: join(__dirname, '..', 'public'),
prefix: '/public/',
});
app.setViewEngine({
engine: {
handlebars: require('handlebars'),
},
templates: join(__dirname, '..', 'views'),
});
await app.listen(3000);
}


bootstrap();