2014-05-11 11 views
56

Sto lavorando alla configurazione di un server http utilizzando node.js e engine. Tuttavia, continuo a imbattersi in problemi che ho poche informazioni su come risolvere apprezzerei un po 'di aiuto per risolvere questo problema. Grazie in anticipo.Errore: non è stato specificato alcun motore predefinito e non è stata fornita alcuna estensione

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) 

Di seguito è quello che ho impostato per avviare questo motore.

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'); 
}; 

risposta

55

vi manca il motore di visualizzazione, per esempio, utilizzare jade:

cambiare la vostra

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

con

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

Se si desidera utilizzare un html uso della sintassi amichevole invece ejs

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

EDIT

Come si può leggere dal view.js espresso View Modulo

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); 
} 

È necessario aver installato un default engine

Express ricerca visualizzazione layout di default, come si program.template può leggere qui sotto:

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; 

     } 
    }); 

e come potete leggere qui di seguito: motore di visualizzazione

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

il valore predefinito è jade

+2

Ciao, puoi spiegare ulteriormente come funziona? Ho iniziato a leggere su node.js, pensando che fosse tutto ciò di cui avevo bisogno, ma quando ancora non riuscivo a visualizzare le mie pagine, ho cercato il motivo e sono arrivato a info su express. Ora ho seguito le informazioni sulla pagina Express 4.2 e ho trovato l'errore sopra il quale mi hai aiutato. Ora ho ejs e non sembra essere tutto ciò di cui ho bisogno. Puoi per favore darmi un flusso di come dovrebbe funzionare, per favore? – Kobojunkie

+0

Ti consiglio di leggere questo tutorial passo passo http://utahjs.com/2010/09/25/nodejs-express-and-ejs-templates/ o questo http://robdodson.me/blog/2012/05/31/how-to-use-ejs-in-express/ – InferOn

+0

Avevo pensato di leggere che è necessario definire esplicitamente un motore di visualizzazione anche se si notano le viste di rendering. non è questo il caso però. – stevejpurves

10

Commentare le res.render righe nel codice e aggiungere in next(err); invece. Se non stai utilizzando un motore di visualizzazione, la roba res.render genererà un errore.

Siamo spiacenti, si dovrà commentare questa linea così:

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

La mia soluzione comporterebbe non utilizzando un motore di vista però. Non hai bisogno di un motore di visualizzazione, ma se questo è l'obiettivo, provate questo:

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

è necessario il res.render linee quando si utilizza un motore di visualizzazione pure. Qualcosa di simile:

// 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: {} 
    }); 
}); 
0

Ho appena ricevuto questo messaggio di errore, e il problema era che non stavo configurando correttamente il mio middleware.

Sto creando un blog nello stack MEAN e ho avuto bisogno dell'analisi del corpo per i file .jade che stavo usando sul lato front-end. Ecco il frammento di codice dal mio "/middleware/index.js "file dal mio progetto

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})); 

Inoltre, ecco il mio" package.json "di file, si può utilizzare diverse versioni di tecnologie . Nota: perché non sono sicuro delle dipendenze tra di loro, io includo l'intero file qui:!!

"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" 
    } 

Spero che questo aiuti qualcuno Tutto il meglio

0

le risposte di cui sopra sono corrette, ma ho scoperto che un semplice errore di battitura può anche gene valuta questo errore. Ad esempio, ho avuto var router = express() invece di var router = express.Router() e ho ricevuto questo errore. Quindi dovrebbe essere il seguente:

// 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'); 
}) 
43

Il materiale res.render genera un errore se non si utilizza un motore di visualizzazione.

Se si desidera solo servire JSON sostituire le res.render('error', { error: err }); righe nel codice con:

res.json({ error: err }) 

PS: Le persone hanno di solito anche un messaggio in oggetto restituito:

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

Se si desidera rendere utilizzare un file html

response.sendfile('index.html'); 

quindi si rimuove del

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

l'unica cosa è mettere il tuo index.html in viste. o fare cartella pubblica come qualcosa di statico e mettere il file index.html in pubblico

+0

'response.sendfile()' è deprecato, usa invece 'response.sendFile()'. Si noti che la capitale "F". –

1

Se tutto ciò che serve è quello di inviare il codice HTML inline nel codice, possiamo usare sotto

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

È possibile utilizzare Express-degli errori gestore di utilizzare pagine html statiche per la gestione degli errori e per evitare di definire un gestore di viste.

L'errore era probabilmente causato da una 404, forse una favicon mancante (apparente se avessi incluso il precedente messaggio della console). Il "gestore di viste" di "html" non sembra essere valido in 4.x express.

Indipendentemente dalla causa, è possibile evitare di definire un gestore di viste (valido) finché si modificano elementi aggiuntivi della configurazione.

Le opzioni disponibili sono per risolvere questo problema sono:

  • definire una vista gestore valida come in altre risposte
  • Usa send(), invece di rendere per restituire il contenuto direttamente

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

L'utilizzo del rendering senza un percorso file richiama automaticamente un gestore di viste con le seguenti due linee dalla configurazione:

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

e:

res.render('500); 

Assicurarsi di installare espresso-error-handler con:

npm install --save express-error-handler 

Quindi importare nei tuoi app.js

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

Poi modificare la gestione degli errori da utilizzare:

// 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); 
Problemi correlati