我正在学习NodeJS,并且正在按照教程为自己创建一个待办事项列表,在此过程中我能够呈现页面,但是当我在添加一些条目后尝试重定向时,会抛出res.redirect而不是功能错误,我找不到解决此问题的简单解决方案。我在这里粘贴完整的代码(第73行,最后一行的第五行抛出错误)
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var expressValidator = require('express-validator')
var app = express();
var mongojs = require('mongojs');
var db = mongojs('mytodolist', ['items'])
// set up the logger
var logger = function(req,res,next){
console.log('its the logger ....');
next();
}
app.use(logger);
// set up view engine
app.set('view engine', 'ejs');
app.set('views',path.join(__dirname, 'views'));
// Body Parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
/* used items until hooked mongo db instance
var items = [
{
id: 1,
task_desc: 'task one',
priority: 'P1',
ETA: 'Jan 31',
},
{
id: 2,
task_desc: 'task two',
priority: 'P2',
ETA: 'Feb 06',
},
{
id: 1,
task_desc: 'task three',
priority: 'P3',
ETA: 'March 1',
},
]
*/
app.get('/', function(req, res){
//res.send('Hello World again');
// find everything
db.items.find(function (err, docs) {
// docs is an array of all the documents in mycollection
//console.log(docs);
res.render('index',{
title: 'My To Do List',
//items: items - "until mongo was hooked up"
items: docs
});
})
});
//add express validator
app.post('/items/add', function(req,res){
var newItem = {
task_desc: req.body.task_desc,
priority: req.body.priority,
ETA: req.body.ETA
}
//console.log(newItem);
db.items.insert(newItem, function(err, res){
if(err){
console.log(err);
}
return res.redirect('/'); // THIS LINE BREAKS
});
});
app.listen(3000, function(){
console.log('server started on port 3000...')
})
节点专家:非常感谢您的帮助。在此先感谢一吨。 :)
答案 0 :(得分:0)
您要覆盖res
变量。
app.post('/items/add', function(req,res){
上面一行中的res
变量被以下内容遮盖:
db.items.insert(newItem, function(err, res){
因此,只需更改变量名称。这样的事情应该起作用:
db.items.insert(newItem, function(err, data){