我正在尝试通过Express学习新知识,目前,我希望能够显示快速消息。我添加了Flash,会话和表达消息作为依赖项,并添加了消息作为局部变量。
在Pug中,我添加了!= messages('message'。locals),根据本教程,这应该已将带有消息的div元素输出,但是不幸的是,当我将其抛出“ messages is a function”错误试图运行它。我想服务器端index.js文件中的req.flash('info','Article Added')将触发该消息。
this is the screenshot of the error I keep getting
请检查我的代码中是否有任何错误,是否卡在这里。我已经做了很多尝试,以找出是什么原因造成的。
这是我的app.js文件
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const expressValidator = require('express-validator');
const session = require('express-session');
const flash = require('connect-flash');
mongoose.connect('mongodb://localhost:27017/nodekb', { useNewUrlParser: true });
const db = mongoose.connection;
const app = express();
// app.dynamicHelpers({ messages: require('express-messages') });
//checking for db's connection
db.once('open', () => {
console.log('connected to mongo db');
});
//checking for db errors
db.on('error', (err) => {
console.log(err);
});
//setting up view engine directories
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
//bring in model
let Article = require('./models/articles')
//express routing and using the article model for home page
app.get('/', (req, res) => {
Article.find({}, (err, articles) => {
if (err) {
console.log(err)
} else {
res.render('index', {
title: 'Article',
articles: articles
});
}
});
});
//body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
//seet public folder
app.use(express.static(path.join(__dirname, 'Public')));
//express session middleware
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
}))
//express message middleware
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
//
app.use(expressValidator({
errorFormatter: (param, msg, value) => {
var namespace = param.split('.'),
root = namespace.shift(),
formParam = root;
while (namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param: formParam,
msg: msg,
value: value
}
}
}))
//another route to add article
app.get('/article/add', (req, res) => {
res.render('add_article', {
title: 'Add Article'
});
});
//get single article
app.get('/article/:id', (req, res) => {
Article.findById(req.params.id, (err, article) => {
res.render('article', {
article: article
})
return;
});
});
//edit single article
app.get('/article/edit/:id', (req, res) => {
Article.findById(req.params.id, (err, article) => {
res.render('edit_article', {
title: 'Edit Article',
article: article
})
return;
});
});
//submit POST form from add_article.pug
app.post('/article/add', (req, res) => {
let article = new Article();
article.title = req.body.title;
article.author = req.body.author;
article.body = req.body.body;
article.save((err) => {
if (err) {
console.log(err);
} else {
req.flash('info', 'Article Added');
// res.send(article);
res.redirect('/');
}
})
});
//update POST form from edit_article.pug
app.post('/article/add/edit/:id', (req, res) => {
let article = {};
let query = { _id: req.params.id }
article.title = req.body.title;
article.author = req.body.author;
article.body = req.body.body;
Article.update(query, article, (err) => {
if (err) {
console.log(err);
} else {
req.flash('info', 'Article updated');
res.redirect('/');
}
})
});
app.delete('/article/:id', (req, res) => {
let query = { _id: req.params.id }
Article.remove(query, (err) => {
if (err) {
console.log(err);
};
res.send('sucess')
})
})
//setting up port
app.listen(3000, () => {
console.log('runnig on port 3000');
})
module.exports = app;
这是我正在使用消息的layout.pug
doctype html
html
head
title Knowledge base
link(rel='stylesheet', href='/bower_components/bootstrap/dist/css/bootstrap.css')
link(rel='stylesheet', href='/css/style.css')
body
nav.navbar.navbar-dark.bg-dark.navbar-expand-md
a.navbar-brand(href='#') Knowledge Base
button.navbar-toggler(type='button', data-toggle='collapse', data-target='#navbarsExample01', aria-controls='navbarsExample01', aria-expanded='false', aria-label='Toggle navigation')
span.navbar-toggler-icon
#navbarsExample01.collapse.navbar-collapse
ul.navbar-nav.ml-auto.pr-3
li.mr-2
a(href='/') Home
span.sr-only (current)
li.mr-2
a(href='/article/add') Add Articles
.container
!= messages('message', locals)
block content
br
hr
footer
p copyright © 2018
script(src='/bower_components/jquery/dist/jquery.js')
script(src='/bower_components/bootstrap/dist/js/bootstrap.js')
script(src='/js/main.js')
最后是Layout.pug中引用的message.pug文件
.messages
each type in Object.keys({messages})
each message in Object.values({messages})
div(class="alert alert-" +type) #{message}
答案 0 :(得分:0)
您需要安装库express-messages