无法呈现express-handelbars模板

时间:2018-05-23 18:46:52

标签: node.js express express-handlebars

我是节点的新手,并且难以获得一个简单的express-handlebar来呈现静态html页面:

require('./config/config');
const path = require('path');
const http = require('http');

const _ = require('lodash');
const express = require('express');
const bodyParser = require('body-parser');
const {ObjectID} = require('mongodb');
const socketIO = require('socket.io');
const exphbs  = require('express-handlebars');


var {mongoose} = require('./db/mongoose');
var {Todo} = require('./models/todo');
var {User} = require('./models/user');
var {authenticate} = require('./middleware/authenticate');

var app = express();
var server = http.createServer(app);
var io =socketIO(server);


const port = process.env.PORT;
const publicPath = path.join(__dirname, './public');

app.use(bodyParser.json());

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', exphbs);
app.use(express.static(publicPath));

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

而不是index.html位于views文件夹中,我收到此错误:

Error: Cannot find module 'function exphbs(config) {
    return create(config).engine;
}'
    at Function.Module._resolveFilename (module.js:538:15)
    at Function.Module._load (module.js:468:25)
    at Module.require (module.js:587:17)
    at require (internal/module.js:11:18)
    at new View (/home/me/nodechatapp/node_modules/express/lib/view.js:81:14)
    at Function.render (/home/me/nodechatapp/node_modules/express/lib/application.js:570:12)
    at ServerResponse.render (/home/me/nodechatapp/node_modules/express/lib/response.js:1008:7)
    at app.get (/home/me/nodechatapp/server.js:37:7)
    at Layer.handle [as handle_request] (/home/me/nodechatapp/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/me/nodechatapp/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/me/nodechatapp/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/me/nodechatapp/node_modules/express/lib/router/layer.js:95:5)
    at /home/me/nodechatapp/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/home/me/nodechatapp/node_modules/express/lib/router/index.js:335:12)
    at next (/home/me/nodechatapp/node_modules/express/lib/router/index.js:275:10)
    at SendStream.error (/home/me/nodechatapp/node_modules/serve-static/index.js:121:7)

这里有什么问题?我该如何解决?

1 个答案:

答案 0 :(得分:2)

我很确定你错过了服务器设置中的app.engine()电话。根据您需要的docs

app.engine('handlebars', exphbs({defaultLayout: 'main'})); app.set('view engine', 'handlebars');

您已将app.set用于视图引擎,但我认为您需要调用前一行。