按照nodejs开发指南中的代码,发布微博等功能已经开发完成,回头运行注册等页面,其中127.0.0.1:8000/reg(post)页面中部分代码会重复执行,并且服务器报错。
报错信息如下: events.js:72 throw er; // Unhandled ‘error’ event ^ Error: Can’t set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (http.js:692:11) at ServerResponse.res.setHeader (/home/cplatform/node/node-0.10.19/webapp/microblog/node_modules/express/node_modules/connect/lib/patch.js:59:22) at ServerResponse.res.set.res.header (/home/cplatform/node/node-0.10.19/webapp/microblog/node_modules/express/lib/response.js:527:10) at ServerResponse.res.location (/home/cplatform/node/node-0.10.19/webapp/microblog/node_modules/express/lib/response.js:661:8) at ServerResponse.res.redirect (/home/cplatform/node/node-0.10.19/webapp/microblog/node_modules/express/lib/response.js:703:8) at /home/cplatform/node/node-0.10.19/webapp/microblog/routes/index.js:84:5 at /home/cplatform/node/node-0.10.19/webapp/microblog/node_modules/user.js:31:3 at /home/cplatform/node/node-0.10.19/webapp/microblog/node_modules/mongodb/lib/mongodb/collection.js:347:9 at Server.Base._callHandler (/home/cplatform/node/node-0.10.19/webapp/microblog/node_modules/mongodb/lib/mongodb/connection/base.js:382:41) at /home/cplatform/node/node-0.10.19/webapp/microblog/node_modules/mongodb/lib/mongodb/connection/server.js:472:18
/routes/index.js 中/reg代码如下: app.post('/reg’, checkNotLogin); app.post('/reg’,function(req,res){ if(req.body[‘password-repeat’] != req.body[‘password’]){ req.flash(‘error’,’两次输入的口令不一致’); return res.redirect(‘/reg’); } var md5 =crypto.createHash(‘md5’); var password = md5.update(req.body.password).digest(‘base64’);
var newUser = new User({ name: req.body.username, password:password, }); User.get(newUser.name, function(err, user){ if(user) err = 'Username already exists.’; if(err){ req.flash('error’, err); return res.redirect(‘/reg’); } newUser.save(function(err){ if(err){ req.flash('error’, err); return res.redirect(‘/reg’); } console.log(‘jjjjjjjjjjjj’); req.session.user = newUser; console.log(req.session.user); req.flash('success’, ‘reg success’) res.redirect(‘/’); }); }); });
其中运行两次的部分为: jjjjjjjjjjjj { name: 'rr’, password: ‘UU8bQ59AT4b3cJD6ntyWzg==’ } POST /reg 302 16ms - 68b jjjjjjjjjjjj { name: 'rr’, password: ‘UU8bQ59AT4b3cJD6ntyWzg==’ }
百思不得其姐,求各位大神指点迷津