简体   繁体   中英

Express-handlebars error - HandleBars is not a function

I keep getting "app.engine('handlebars', handlebars()); type error 'handlebars' is not a function? Is there anything wrong in my code?

const express = require('express');

const nodemailer = require("nodemailer");
const paths = require('path'); 
const handlebars = require('express-handlebars')



const app = express();
require("dotenv").config();

//View engine setup
app.set("view engine", 'handlebars');
app.engine('handlebars', handlebars());

//Static Folder
app.use('/public', express.static(path.join(__dirname, 'public')))


//Body Parser MiddleWars;

app.use(express.urlencoded({extended: false}));
app.use(express.json())
const port = 3001;
app.listen(port, () => { 
    console.log(`Server is running on port: ${port}`); 
}); 

According to the examples express-handlebars provided, you must import the engine function from the module:

(Using Imports)

import express from 'express';
import { engine } from 'express-handlebars';

const app = express();

app.engine('handlebars', engine());
app.set('view engine', 'handlebars');
app.set("views", "./views");

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

app.listen(3000);

So, instead of calling handlebars directly, you should be calling handlebars.engine .

In total:

const express = require('express');

const nodemailer = require("nodemailer");
const paths = require('path'); 
const handlebars = require('express-handlebars')



const app = express();
require("dotenv").config();

//View engine setup
app.set("view engine", 'handlebars');
app.engine('handlebars', handlebars.engine());

//Static Folder
app.use('/public', express.static(path.join(__dirname, 'public')))


//Body Parser MiddleWars;

app.use(express.urlencoded({extended: false}));
app.use(express.json())
const port = 3001;
app.listen(port, () => { 
    console.log(`Server is running on port: ${port}`); 
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM