做完番外篇之——使用 _id 查询后,试着发表一篇文章,启动npm start报这个错 package.json { “name”: “blog”, “version”: “0.0.0”, “private”: true, “scripts”: { “start”: “node ./bin/www” }, “dependencies”: { “body-parser”: “~1.13.2”, “connect-flash”: “^0.1.1”, “connect-mongo”: “^1.0.1”, “cookie-parser”: “~1.3.5”, “debug”: “~2.2.0”, “ejs”: “~2.3.3”, “express”: “~4.13.1”, “express-session”: “^1.12.1”, “markdown”: “^0.5.0”, “mongodb”: “^2.0.52”, “morgan”: “~1.6.1”, “multer”: “0.1.6”, “serve-favicon”: “~2.3.0” } } app.js var express = require(‘express’); var path = require(‘path’); var favicon = require(‘serve-favicon’); var logger = require(‘morgan’); var cookieParser = require(‘cookie-parser’); var bodyParser = require(‘body-parser’); var session = require(‘express-session’); var MongoStore = require(‘connect-mongo’)(session); var multer = require(‘multer’);
var routes = require(’./routes/index’); var settings = require(’./settings’); var flash = require(‘connect-flash’); var users = require(’./routes/users’);
var fs = require(‘fs’); var accessLog = fs.createWriteStream(‘access.log’, {flags: ‘a’}); var errorLog = fs.createWriteStream(‘error.log’, {flags: ‘a’});
var app = express();//生成一个express实例 app
// view engine setup app.set(‘views’, path.join(__dirname, ‘views’)); app.set(‘view engine’, ‘html’); app.use(flash()); app.engine(’.html’, require(‘ejs’).__express);
// uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, ‘public’, ‘favicon.ico’))); app.use(logger(‘dev’)); app.use(logger({stream: accessLog})); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, ‘public’))); app.use(function (err, req, res, next) { var meta = ‘[’ + new Date() +’] ’ + req.url + ‘\n’; errorLog.write(meta + err.stack + ‘\n’); next(); }); app.use(session({ resave: false, saveUninitialized: true, secret: settings.cookieSecret, key: settings.db,//cookie name cookie: {maxAge: 100060602430},//30 days store: new MongoStore({ url: ‘mongodb://localhost/blog’, db: settings.db, host: settings.host, port: settings.port }) })); app.use(multer({ dest: ‘./public/images’, rename: function (fieldname, filename) { return filename; } }));
app.use(’/’, routes);//加载路由 app.use(’/users’, users);
// catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error(‘Not Found’); err.status = 404; next(err); });
// 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); res.render(‘error’, { message: err.message, error: {} }); });
module.exports = app;//导出app实例供其他模块调用 index.js var crypto = require(‘crypto’), User = require(’…/models/user.js’); Post = require(’…/models/post.js’); Comment = require(’…/models/comment.js’); var express = require(‘express’); var router = express.Router();
/* GET index page. */ router.get(’/’, function (req, res) { var page = parseInt(req.query.p) || 1; Post.getTen(null, page, function (err, posts, total) { if (err) { posts = []; } res.render(‘index’, { title: ‘主页’, posts: posts, page: page, isFirstPage: (page - 1) == 0, isLastPage: ((page - 1) * 10 + posts.length) == total, user: req.session.user, success: req.flash(‘success’).toString(), error: req.flash(‘error’).toString() }); }); });
router.get(’/reg’, checkNotLogin); router.get(’/reg’, function (req, res) { res.render(‘reg’, { title: ‘注册’, user: req.session.user, success: req.flash(‘success’).toString(), error: req.flash(‘error’).toString() }); });
router.post(’/reg’, checkNotLogin); router.post(’/reg’, function (req, res) { var name = req.body.name, password = req.body.password, password_re = req.body[‘password-repeat’]; if (password_re != password) { req.flash(‘error’, ‘两次输入的密码不一致!’); return res.redirect(’/reg’); } var md5 = crypto.createHash(‘md5’), password = md5.update(req.body.password).digest(‘hex’); var newUser = new User({ name: name, password: password, email: req.body.email }); User.get(newUser.name, function (err, user) { if (err) { req.flash(‘error’, err); return res.redirect(’/’); } if (user) { req.flash(‘error’, ‘用户已存在!’); return res.redirect(’/reg’); } newUser.save(function (err, user) { if (err) { req.flash(‘error’, err); return res.redirect(’/reg’); } req.session.user = user; req.flash(‘success’, ‘注册成功!’); res.redirect(’/’); }); }); });
router.get(’/login’, checkNotLogin); router.get(’/login’, function (req, res) { res.render(‘login’, { title: ‘登录’, user: req.session.user, success: req.flash(‘success’).toString(), error: req.flash(‘error’).toString()}); });
router.post(’/login’, checkNotLogin); router.post(’/login’, function (req, res) { var md5 = crypto.createHash(‘md5’), password = md5.update(req.body.password).digest(‘hex’); User.get(req.body.name, function (err, user) { if (!user) { req.flash(‘error’, ‘用户不存在!’); return res.redirect(’/login’); } if (user.password != password) { req.flash(‘error’, ‘密码错误!’); return res.redirect(’/login’); } req.session.user = user; req.flash(‘success’, ‘登录成功!’); res.redirect(’/’) }); });
router.get(’/post’, checkLogin); router.get(’/post’, function (req, res) { res.render(‘post’, { title: ‘发表’, user: req.session.user, success: req.flash(‘success’).toString(), error: req.flash(‘error’).toString() }); });
router.post(’/post’, checkLogin); router.post(’/post’, function (req, res) { var currentUser = req.session.user, tags = [req.body.tag1, req.body.tag2, req.body.tag3], post = new Post(currentUser.name, currentUser.head, req.body.title, tags, req.body.post); post.save(function (err) { if (err) { req.flash(‘error’, err); return res.redirect(’/’); } req.flash(‘success’, ‘发布成功!’); res.redirect(’/’); }); });
router.get(’/logout’, checkLogin); router.get(’/logout’, function (req, res) { req.session.user = null; req.flash(‘success’, ‘退出成功!’); res.redirect(’/’); });
router.get(’/upload’, checkLogin); router.get(’/upload’, function (req, res) { res.render(‘upload’, { title: ‘文件上传’, user: req.session.user, success: req.flash(‘success’).toString(), error: req.flash(‘error’).toString() }); });
router.post(’/upload’, checkLogin); router.post(’/upload’, function (req, res) { req.flash(‘success’, ‘文件上传成功!’); res.redirect(’/upload’); })
router.get(’/archive’, function (req, res) { Post.getArchive(function (err, posts) { if (err) { req.flash(‘error’, err); return res.redirect(’/’); } res.render(‘archive’, { title: ‘存档’, posts: posts, user: req.session.user, success: req.flash(‘success’).toString(), error: req.flash(‘error’).toString() }); }); });
router.get(’/tags’, function (req, res) { Post.getTags(function (err, posts) { if (err) { req.flash(‘error’, err); return res.redirect(’/’); } res.render(‘tags’, { title: ‘标签’, posts: posts, user: req.session.user, success: req.flash(‘success’).toString(), error: req.flash(‘error’).toString() }); }); });
router.get(’/tags/:tag’, function (req, res) { Post.getTag(req.params.tag, function (err, posts) { if (err) { req.flash(‘error’, err); return res.redirect(’/’); } res.render(‘tag’, { title: 'TAG: ’ + req.params.tag, posts: posts, user: req.session.user, success: req.flash(‘success’).toString(), error: req.flash(‘error’).toString() }); }); });
router.get(’/links’, function (req, res) { res.render(‘links’, { title: ‘友情链接’, user: req.session.user, success: req.flash(‘success’).toString(), error: req.flash(‘error’).toString() }); });
router.get(’/search’, function (req, res) { Post.search(req.query.keyword, function (err, posts) { if (err) { req.flash(‘error’, err); return res.redirect(’/’); } res.render(‘search’, { title: “SEARCH:” + req.query.keyword, posts: posts, user: req.session.user, success: req.flash(‘success’).toString(), error: req.flash(‘error’).toString() }); }); });
router.get(’/u/:name’, function (req, res) { var page = parseInt(req.query.p) || 1; User.get(req.params.name, function (err, user) { if (!user) { req.flash(‘error’, ‘用户不存在!’); return res.redirect(’/’); } Post.getTen(user.name, page, function (err, posts, total) { if (err) { req.flash(‘error’, err); return res.redirect(’/’); } res.render(‘user’, { title: user.name, posts: posts, page: page, isFirstPage: (page - 1) == 0, isLastPage: ((page - 1) * 10 + posts.length) == total, user: req.session.user, success: req.flash(‘success’).toString(), error: req.flash(‘error’).toString() }); }); }); });
router.get(’/p/:_id’, function (req, res) { Post.getOne(req.params._id, function (err, post) { if (err) { req.flash(‘error’, err); return res.redirect(’/’); } res.render(‘article’, { title: post.title, post: post, user: req.session.user, success: req.flash(‘success’).toString(), error: req.flash(‘error’).toString() }); }); });
router.post(’/u/:name/:day/:title’, function (req, res) {
var date = new Date(),
time = date.getFullYear() + “-” + (date.getMonth() + 1) + “-” + date.getDate() + " " +
date.getHours() + “:” + (date.getMinutes() < 10 ? ‘0’ + date.getMinutes() : date.getMinutes());
var md5 = crypto.createHash(‘md5’),
email_MD5 = md5.update(req.body.email.toLowerCase()).digest(‘hex’),
head = “http://www.gravatar.com/avatar/” + email_MD5 + “?s=48”;
var comment = {
name: req.body.name,
head: head,
email: req.body.email,
website: req.body.website,
time: time,
content: req.body.content
};
var newComment = new Comment(req.params.name, req.params.day, req.params.title, comment);
newComment.save(function (err) {
if (err) {
req.flash(‘error’, err);
return res.redirect(‘back’);
}
req.flash(‘success’, ‘留言成功!’);
res.redirect(‘back’);
});
});
router.get(’/edit/:name/:day/:title’, checkLogin); router.get(’/edit/:name/:day/:title’, function (req, res) { var currentUser = req.session.user; Post.edit(currentUser.name, req.params.day, req.params.title, function (err, post) { if (err) { req.flash(‘error’, err); return res.redirect(‘back’); } res.render(‘edit’, { title: ‘编辑’, post: post, user: req.session.user, success: req.flash(‘success’).toString(), error: req.flash(‘error’).toString() }); }); });
router.post(’/edit/:name/:day/:title’, checkLogin); router.post(’/edit/:name/:day/:title’, function (req, res) { var currentUser = req.session.user; Post.update(currentUser.name, req.params.day, req.params.title, req.body.post, function (err) { var url = encodeURI(’/u/’ + req.params.name + ‘/’ + req.params.day + ‘/’ + req.params.title); if (err) { req.flash(‘error’, err); return res.redirect(url); } req.flash(‘success’, ‘修改成功!’); res.redirect(url); }); });
router.get(’/remove/:name/:day/:title’, checkLogin); router.get(’/remove/:name/:day/:title’, function (req, res) { var currentUser = req.session.user; Post.remove(currentUser.name, req.params.day, req.params.title, function (err) { if (err) { req.flash(‘error’, err); return res.redirect(‘back’); } req.flash(‘success’, ‘删除成功!’); res.redirect(’/’); }); });
router.get(’/reprint/:name/:day/:title’, checkLogin);
router.get(’/reprint/:name/:day/:title’, function (req, res) {
Post.edit(req.params.name, req.params.day, req.params.title, function (err, post) {
if (err) {
req.flash(‘error’, err);
return res.redirect(back);
}
var currentUser = req.session.user,
reprint_from = {name: post.name, day: post.time.day, title: post.title},
reprint_to = {name: currentUser.name, head: currentUser.head};
Post.reprint(reprint_from, reprint_to, function (err, post) {
if (err) {
req.flash(‘error’, err);
return res.redirect(‘back’);
}
req.flash(‘success’, ‘转载成功!’);
var url = encodeURI(’/u/’ + post.name + ‘/’ + post.time.day + ‘/’ + post.title);
res.redirect(url);
});
});
});
router.use(function (req, res) { res.render(“404”); });
function checkLogin(req, res, next) { if (!req.session.user) { req.flash(‘error’, ‘未登录!’); res.redirect(’/login’); } next(); }
function checkNotLogin(req, res, next) { if (req.session.user) { req.flash(‘error’, ‘已登录!’); res.redirect(‘back’); } next(); }
module.exports = router;