在快速车把中配置文件扩展名

时间:2019-01-26 15:41:47

标签: javascript express express-handlebars

我有车把配置

const path = require('path')
const exphbs = require('express-handlebars')

const morgan = require('morgan');
const multer = require('multer');
const express = require('express');
const erroHandler = require('errorhandler')
const routes = require('../routes/index');

module.exports = app => {

    app.set('port', process.env.PORT || 80) 
    app.set('views', path.join(__dirname, '../views'));
    app.engine('.hbs', exphbs({
        defaultLayout: 'main',
        partialsDir: path.join(app.get('views'), 'partials' ),
        layoutDir: path.join(app.get('views'), 'layouts'),
        helpers: require('../helpers')
    }))
    app.set('view engine', '.hbs');


    // middlewares
    app.use(morgan('dev'));
    app.use(multer({dest: path.join(__dirname, '../public/upload/temp')}).single('image'))
    app.use(express.urlencoded({extended: false}));
    app.use(express.json());

    //routes
    routes(app)

    // static files
    app.use('/public', express.static(path.join(__dirname, '../public')));


    // errorhandlers
    if ('development' === app.get('env')) {
        app.use(erroHandler)
    }

    return app;
}

但我收到此错误:

  

错误:ENOENT:没有此类文件或目录,请打开'C:\ Users \ Diesan   Romero \ Desktop \ redsocial \ views \ layouts \ main.handlebars'

这是我的目录,怎么了? enter image description here

1 个答案:

答案 0 :(得分:1)

由于把手文件使用.hbs作为扩展名,因此在实例化把手时需要正确定义extName,如下所示:

exphbs.create({
    extname: '.hbs',
    // rest of options
})

或者修改您的代码:

app.engine('.hbs', exphbs({
    extName: '.hbs',
    defaultLayout: 'main',
    partialsDir: path.join(app.get('views'), 'partials' ),
    layoutDir: path.join(app.get('views'), 'layouts'),
    helpers: require('../helpers')
}))

或者只是将您的车把文件扩展名更改为filename.handlebars