使用 Express + MongoDB 搭建多人博客
- Node.js:
8.9.1
- MongoDB:
3.4.10
- Express:
4.16.2
- 开发环境搭建
- Node.js 知识点讲解
- Hello, Express
- 一个简单的博客
您的捐赠,是我持续开源的动力。
支付宝 | 微信 |
---|---|
《一起学 Node.js》
Express
500 ReferenceError: d:\nodejs\blog\views\index.ejs:2 1| <%- include header %> >> 2| <% posts.forEach(function(post,index){ %> 3|
5| 作者:<%= post.name %> | posts is not defined
1| <%- include header %>
2| <% posts.forEach(function(post,index){ %>
3|
<%= post.title %>
4|
5| 作者:<%= post.name %> |
posts is not defined
at eval (eval at (d:\nodejs\blog\node_modules\ejs\lib\ejs.js:236:14), :31:52)
at eval (eval at (d:\nodejs\blog\node_modules\ejs\lib\ejs.js:236:14), :33:35)
at d:\nodejs\blog\node_modules\ejs\lib\ejs.js:249:15
at Object.exports.render (d:\nodejs\blog\node_modules\ejs\lib\ejs.js:287:13)
at View.exports.renderFile as engine
at View.render (d:\nodejs\blog\node_modules\express\lib\view.js:76:8)
at Function.app.render (d:\nodejs\blog\node_modules\express\lib\application.js:505:10)
at ServerResponse.res.render (d:\nodejs\blog\node_modules\express\lib\response.js:756:7)
at d:\nodejs\blog\routes\index.js:20:7
at callbacks (d:\nodejs\blog\node_modules\express\lib\router\index.js:161:37)
node app.js
2014-01-05T18:26:28.637200+00:00 app[web.1]: > [email protected] start /app
2014-01-05T18:26:28.637204+00:00 app[web.1]:
2014-01-05T18:26:28.949332+00:00 app[web.1]: Express server listening on port 14713
2014-01-05T18:26:29.322966+00:00 heroku[web.1]: State changed from starting to up
2014-01-05T18:26:34.854945+00:00 app[web.1]:
2014-01-05T18:26:34.855528+00:00 app[web.1]: throw new Error('Error connecting to database');
2014-01-05T18:26:34.855547+00:00 app[web.1]: ^
2014-01-05T18:26:34.858285+00:00 app[web.1]: Error: Error connecting to database
2014-01-05T18:26:34.858288+00:00 app[web.1]: at /app/node_modules/connect-mongo/lib/connect-mongo.js:176:17
2014-01-05T18:26:34.858291+00:00 app[web.1]: at /app/node_modules/mongodb/lib/mongodb/db.js:273:18
2014-01-05T18:26:34.858293+00:00 app[web
.1]: at /app/node_modules/mongodb/lib/mongodb/db.js:351:18
2014-01-05T18:26:34.858295+00:00 app[web.1]: at Server.close (/app/node_modules/mongodb/lib/mongodb/connection/server.js:210:38)
2014-01-05T18:26:34.858296+00:00 app[web.1]: at Db.close (/app/node_modules/mongodb/lib/mongodb/db.js:347:21)
2014-01-05T18:26:34.858298+00:00 app[web.1]: at /app/node_modules/mongodb/lib/mongodb/db.js:271:21
2014-01-05T18:26:34.858300+00:00 app[web.1]: at null. (/app/node_modules/mongodb/lib/mongodb/connection/server.js:563:7)
2014-01-05T18:26:34.858301+00:00 app[web.1]: at EventEmitter.emit (events.js:106:17)
2014-01-05T18:26:34.858303+00:00 app[web.1]: at null. (/app/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:140:15)
2014-01-05T18:26:34.858304+00:00 app[web.1]: at EventEmitter.emit (events.js:98:17)
2014-01-05T18:26:34.867250+00:00 app[web.1]:
2014-01-05T18:26:34.872683+00:00 app[web.1]: npm ERR! Exit status 8
2014-01-05T18:26:34.873001+00:00 app[web.1]: npm ERR! Failed at the [email protected] start script.
2014-01-05T18:26:34.873752+00:00 app[web.1]: npm ERR! node app.js
2014-01-05T18:26:34.872824+00:00 app[web.1]: npm ERR!
2014-01-05T18:26:34.873648+00:00 app[web.1]: npm ERR! Tell the author that this fails on your system:
2014-01-05T18:26:34.855280+00:00 app[web.1]: /app/node_modules/connect-mongo/lib/connect-mongo.js:176
2014-01-05T18:26:34.872504+00:00 app[web.1]: npm ERR! [email protected] start:node app.js
2014-01-05T18:26:34.873100+00:00 app[web.1]: npm ERR! This is most likely a problem with the Blog package,
2014-01-05T18:26:34.873556+00:00 app[web.1]: npm ERR! not with npm itself.
2014-01-05T18:26:34.873849+00:00 app[web.1]: npm ERR! You can get their info via:
2014-01-05T18:26:34.873946+00:00 app[web.1]: npm ERR! npm owner ls Blog
2014-01-05T18:26:34.874048+00:00 app[web.1]: npm ERR! There is likely additional logging output above.
2014-01-05T18:26:34.874169+00:00 app[web.1]: npm ERR! System Linux 3.8.11-ec2
2014-01-05T18:26:34.874445+00:00 app[web.1]: npm ERR! command "/app/vendor/node/bin/node" "/app/vendor/node/bin/npm" "start"
2014-01-05T18:26:34.874577+00:00 app[web.1]: npm ERR! cwd /app
2014-01-05T18:26:34.874701+00:00 app[web.1]: npm ERR! node -v v0.10.24
2014-01-05T18:26:34.874826+00:00 app[web.1]: npm ERR! npm -v 1.3.21
2014-01-05T18:26:34.874944+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2014-01-05T18:26:34.876377+00:00 app[web.1]: npm ERR!
2014-01-05T18:26:34.876491+00:00 app[web.1]: npm ERR! Additional logging details can be found in:
2014-01-05T18:26:34.876585+00:00 app[web.1]: npm ERR! /app/npm-debug.log
2014-01-05T18:26:34.876785+00:00 app[web.1]: npm ERR! not ok code 0
2014-01-05T18:26:34.853753+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path=/ host=xthought.herokuapp.com fwd="66.175.221.233" dyno=web.1 connect=0ms service=36ms status=503 bytes=0
2014-01-05T18:26:35.972401+00:00 heroku[web.1]: Process exited with status 1
markdown的写法有问题了,应该是 "node-markdown": "*" ,然后 var markdown = require('markdown').markdown 为 var markdown = require('node-markdown').Markdown、markdown.toHTML("string") 为 markdown("string")
前提:
app.use(express.static(__dirname + '/public'));
疑惑:
//localhost:3000/xx.jpg ok
//localhost:3000/x/xx.jpg ok
//localhost:3000/x/x/xx.jpg error
前面两种资源文件都访问的到,可最后一种资源文件访问不到。请问下是什么原因?
Object # has no method 'redirect'
看到类似问题说跟flash的引入有关,没有解决办法,求大神解答
我的express版本是3.4.7。
完整错误代码:
c:\Users\u\nodejs\blog\node_modules\mongodb\lib\mongodb\connection\base.js:242
throw message;
^
TypeError: Object # has no method 'redirect'
at module.exports.app.get.res.render.title (c:\Users\u\nodejs\blog\routes\in
dex.js:52:8)
at User.save (c:\Users\u\nodejs\blog\models\user.js:38:5)
at c:\Users\u\nodejs\blog\node_modules\mongodb\lib\mongodb\collection\core.j
s:216:9
at Server.Base._callHandler (c:\Users\u\nodejs\blog\node_modules\mongodb\lib
\mongodb\connection\base.js:442:41)
at Server.connect.connectionPool.on.server._serverState (c:\Users\u\nodejs\b
log\node_modules\mongodb\lib\mongodb\connection\server.js:485:18)
at MongoReply.parseBody (c:\Users\u\nodejs\blog\node_modules\mongodb\lib\mon
godb\responses\mongo_reply.js:68:5)
at Server.connect.connectionPool.on.server._serverState (c:\Users\u\nodejs\b
log\node_modules\mongodb\lib\mongodb\connection\server.js:443:20)
at EventEmitter.emit (events.js:96:17)
at _connect (c:\Users\u\nodejs\blog\node_modules\mongodb\lib\mongodb\connect
ion\connection_pool.js:191:13)
at EventEmitter.emit (events.js:99:17)
DEBUG: Program node c:\Users\u\nodejs\blog\app exited with code 1
DEBUG: Starting child process with 'node c:\Users\u\nodejs\blog\app'
Failed to load c++ bson extension, using pure JS version
Express server listening on port 3000
markdown这个插件在转换过程中会为段落添加额外的<p>
标签,直接发送到前端可能会造成困扰,所以服务端需要多做一步处理:
var markdown = require('markdown').markdown
docs.forEach(function (doc) {
var tree = markdown.parse(doc.post)
tree.forEach(function (jsonml) {
// 移除`para`标记
if (jsonml[0] == "para") { jsonml.splice(0,1) } }
})
});
var html = markdown.renderJsonML( markdown.toHTMLTree(tree) );
TypeError: Cannot call method 'slice' of null
对应代码位置:
//解析markdown为html
docs.forEach(function(doc) {
doc.post = markdown.toHTML(doc.post);
});
使用connect-mongo 版本0.3.2
启动程序总是得到下面消息
Please ensure that you set the default write concern for the database by setting =
= one of the options =
…… ……
将连接形式更改了一下
module.exports = new Db(settings.db, new Server(settings.host, Connection.DEFAULT_PORT, {}));
更改为
module.exports = new Db(settings.db, new Server(settings.host, Connection.DEFAULT_PORT, {}), {safe: true});
便正常了。
/models / user.js 里的这一段
User.prototype.save = function(callback) { //要存入数据库的用户文档 var user = { name: this.name, password: this.password, email: this.email }; //打开数据库 mongodb.open(function (err, db) { if (err) { callback(err);//错误,返回 err 信息 } //读取 users 集合 db.collection('users', function (err, collection) { if (err) { mongodb.close(); callback(err);//错误,返回 err 信息 } //将用户数据插入 users 集合 collection.insert(user, {safe: true}, function (err, user) { mongodb.close();//关闭数据库 callback(null);//成功!err 为 null }); }); }); };
if (err) { callback(err);//错误,返回 err 信息 }这个地方为什么不用return callback(err);如果出错了为什么不让函数返回,停止后续的操作?求教
报错信息为:
400 Error: Failed to decode param '2014t1%0818%E5'F100Y%B2,%9B:%CF%08%8C'
应该是res.redirect(url); 对中文的转码有问题
先用encodeURI()对url转码一下,再redirect就解决问题
想问一下,为什么要去掉,把session存储到数据库——去掉key和store。
TypeError: Cannot call method 'forEach' of undefined
at /Users/liqy/node.js/blog/models/post.js:107:24
at /Users/liqy/node.js/blog/node_modules/mongodb/lib/mongodb/collection.js:1012:5
at Cursor.nextObject (/Users/liqy/node.js/blog/node_modules/mongodb/lib/mongodb/cursor.js:677:5)
at commandHandler (/Users/liqy/node.js/blog/node_modules/mongodb/lib/mongodb/cursor.js:658:14)
at null. (/Users/liqy/node.js/blog/node_modules/mongodb/lib/mongodb/db.js:1651:20)
at g (events.js:175:14)
at EventEmitter.emit (events.js:106:17)
at Server.Base._callHandler (/Users/liqy/node.js/blog/node_modules/mongodb/lib/mongodb/connection/base.js:409:25)
at /Users/liqy/node.js/blog/node_modules/mongodb/lib/mongodb/connection/server.js:562:20
at MongoReply.parseBody (/Users/liqy/node.js/blog/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:131:5)
我找这个方法花了几个小时,怕还有人看不到。。
方法:
在setting.js的host的主机名前加“用户名:密码@”
在app.js中
app.use(express.session({
secret: settings.cookieSecret,
key: settings.db,
cookie: {maxAge: 1000 * 60 * 60 * 24 * 30},//30 days
store: new MongoStore({
db: settings.db,
})
}));
在db: setting.db下加入username: '用户名'和password: '密码'
由于connect-mongodb是根据数据库建立连接,所以需要在指定数据库建用户,在admin建立的不能使用
需要在app.js里添加var fs = require('fs');
否则提交会报错。
教程里只提到在index.js里添加。
只有模型的save方法才使用原型来定义,为啥update等其他方法不使用原型来定义呢?
首先感谢您的教程,为我们初学者提供了很好的资料
我在第五章发现有一个问题
这段代码
app.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 = '/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);//成功!返回文章页
});
});
最后的redirect如果url不转码,一旦title是中文字符,那么就会报400
我将url变量改了
var url = '/u/' + req.params.name.trim() + '/' + req.params.day.trim() + '/' + encodeURIComponent(req.params.title.trim());
修复了这个错误。
数据库连接这里是有问题的:
pool.acquire(function (err, mongodb) {
mongodb.open(function (err, db) {
...
pool.release(mongodb);
});
});
每次通过pool acquire了一个连接之后,我们在里面创建了一个mongodb连接,但是并没有销毁它(在pool的destory接口处打个log就知道了)。当并发量达到min属性的参数(例子中是5)就会出现重复打开数据库的错误。
解决方法是我们只在pool的create接口中打开mongo的连接:
create : function(callback) {
var mongodb = Db();
mongodb.open(function (error, db) {
if (error) return callback(error)
callback(null, db);
})
},
后面在pool中acquire/release即可
推荐阅读:mongodb驱动的正确使用方法
failed to load c++ bosn extension , using pure JS version,这个是神马错啊,新手 谢谢指教
如果文章的总数量或某个用户的文章数量为10的倍数,则会出现最后一页的页脚仍然会有“下一页”标签,但实际上下一页是没有内容的。
paging.ejs 中 if(postsLen==10)的判断可能还不够,还要加上其他的判断条件吧。
你好,我的Mongodb部署在其他服务器上 运行代码出现Error connecting to database 错误,settings.js我已经改了,工程能够正常启动,查看Mongodb,名称叫blog的db也已经自动创建了,就是在访问首页的时候报这个错误。能帮帮我么
每个model模块中,都使用了这个方法。
//打开数据库
mongodb.open(function (err, db) {
..............
}
难道对每个请求都要open一次数据库么?
尽快修改吧,我看fork人不少,不要误人子弟啊。哈哈
若在桌面上创建快捷方式启动app。上传图片时报错,提示400 bad request。
不知道是我自己的问题还是教程就没详细说这里
我发现只有存头像到users表, 没看到哪里有取users 表的 head呢
貌似楼主的css有点问题,你再试试看,我后来看了你完整版本里的css,你貌似把之后的版本的css跟着部分的弄乱了,就是那个nav部分的
为什么要用app.use(express.router(routes)) 代替 app.use(app.router),而且代替后会报 has no router方法? 我的express是3.4.7版本
TypeError: /home/nick/Projects/N-blog/views/index.ejs:9
7| 日期:<%= post.time.minute %> |
8| 标签:
>> 9| <% post.tags.forEach(function(tag, index){ %>
10| <% if(tag.tag){ %>
11| <a class="tag" href="/tags/<%= tag.tag %>"><%= tag.tag %></a>
12| <% } %>
Cannot call method 'forEach' of undefined
Error: Cannot use a writeConcern without a provided callback
我照着教程,做到了[注册和登陆] - > [index的设计]这一步
然后运行app,访问localhost:3000。
报出了404的错。这个时候mongodb是连接正常,没有报错。
瞧着好像上connect-mongo出错了。因为提示的信息太少,google,baidu都查不到。请帮忙看看错误原因。
具体错误如下:
Not Found
404
Error: Not Found
at Object.app.use.res.render.message as handle
at next (/Users/dl/Project/blog/node_modules/express/node_modules/connect/lib/proto.js:193:15)
at /Users/dl/Project/blog/node_modules/express/node_modules/connect/node_modules/express-session/index.js:350:9
at /Users/dl/Project/blog/node_modules/connect-mongo/lib/connect-mongo.js:222:17
at /Users/dl/Project/blog/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/collection/query.js:147:5
at Cursor.nextObject (/Users/dl/Project/blog/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/cursor.js:733:5)
at commandHandler (/Users/dl/Project/blog/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/cursor.js:713:14)
at /Users/dl/Project/blog/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/db.js:1806:9
at Server.Base._callHandler (/Users/dl/Project/blog/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection/base.js:442:41)
at /Users/dl/Project/blog/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection/server.js:485:18
在“使用KindEditor”中:
我们也可以使用 KindEditor 默认的(default)编辑器样式,将以上 KindEditor.ready 替换为以下代码即可:
KindEditor.ready(function(K) {
window.editor = K.create('#kindeditor');
});
里面这段代码应该是
var editor;
KindEditor.ready(function(K) {
editor = K.create('textarea');
});
第九章 tag.ejs 是存档页的代码
升级到express 4.x吧
在加入comment之前发表的文章不能回复,且会出现错误
建议在comment.ejs中加入对comments是否存在的判断
文中提到的两个问题:
解决方案个人觉得有很多可完善的部分,可以在session.user中存储用户的账号类型字段(比如:{type:github}),这样相同用户名也可以登录,获取个人博客列表的时候再次检查type字段,如果为github直接跳过用户名的检查(或在数据库中特别存储一个github-username的字段,具体实现不一而足了)
初始化Db(db, new Server(host, post, {safe: true}); 后每次mongo操作都要去open,这样如果多个请求并发时后面的请求open一个还没有被close的数据库都是失败的这个怎么解决。
教程看完,感觉功能已经挺完整了,懒得打一遍代码,请问有代码下么
400 Error: ENOENT, open 'C:\Users\k\Desktop\public\images\5044-srk0ov'
一上传文件有时候前台报错,有时候前台一直处于获取状态,后台报这错,这是为什么啊?
comments.ejs 必须添加 判断语句 <%if(post.comments && post.comments.length>0){%>,否则如果打开一个没有留言的文章的话,会出错
Hi nswbmw,
非常感谢你提供的例子。
刚刚接触nodejs,想做个网站,之前有mvc的经验,看了下express-validator,感觉在里面直接写req.assert很不合适,还有多语言,有没有这么一个插件,直接在function内部就把验证处理完了?
类似于use,不过是基于action的,验证通过了再next,统一验证入口,再加上多语言。
找了很久,都没有合适的,感觉应该在route初始化的时候处理。
希望得到建议,多谢。
还要改"index.ejs"里边标题跟作者的"href",不然没法完成跳转
在点击注册时,无法插入数据!
Error: db object already connecting, open cannot be called multiple times
mongo在save和open时异常!
mac下mongo版本为:2.6.0版本
换了一台ubuntu,没有此错误,查看mongo版本为:2.4.9.
代码无误,无法存储数据!
之前已经提交的文章 post 中没有comments,在添加 comments 后,会提示:TypeError: Cannot call method 'forEach' of undefined
建议在
if(doc){
doc.post = markdown.toHTML(doc.post);
doc.comments.forEach(function(comment){
comment.content = markdown.toHTML(comment.content);
});
}
中增加一个关于 doc.comments 的类型判断。
学习到第三章的时候,替换成
app.use(express.bodyParser({ keepExtensions: true, uploadDir: './public/images' }));
会报错
Error: Cannot find module 'readable-stream'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (D:\blog\node_modules\express\node_modules\connect\nod
e_modules\multiparty\index.js:3:14)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
请问如何解决,搜索了一下,没有解决。
部署到heroku之前的最后一步,在ssh目录创建文件config,
Host heroku.com
User yourName
Hostname 107.21.95.3
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
port 22
第四行 publickey需要自己到heroku去申请吗,去申请key的时候,提示的创建key目录没有key文件。
git push heroku master
出现问题是: permission denied(publickey)
could not read from remote repository
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.