NodeJS : TypeError: res.redirect is not a function

NodeJS : TypeError: res.redirect is not a function

我正在学习 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...')
})

节点专家:非常感谢您的帮助。提前致谢。 :)

您正在覆盖 res 变量。

app.post('/items/add', function(req,res){

上一行中的 res 变量被隐藏:

db.items.insert(newItem, function(err, res){

所以,只需更改变量名称即可。这样的事情应该有效:

db.items.insert(newItem, function(err, data){