无法读取Ajax帖子中未定义的属性“ 0”

时间:2019-03-18 15:51:06

标签: jquery node.js ajax

在ajax POST请求的.fail()函数从服务器接收到错误之后,我的屏幕上出现错误“无法读取未定义的属性'0'”。这是发布路由器的代码:

router.post('/', function (req, res, next) {
var userTasks = req.body.phases[0].tasks;
var tasks = [];
for(var i=0; i<userTasks.length; i++){
    var subTask = {};
    subTask._id = req.body.phases[0].tasks[i].id;
    subTask.name = req.body.phases[0].tasks[i].name;
    subTask.comment = req.body.phases[0].tasks[i].comment;
    subTask.activeTime = req.body.phases[0].tasks[i].activeTime;
    tasks.push(subTask);
}
var phases = {
    _id: req.body.phases[0].id,
    name: req.body.phases[0].name,
    description: req.body.phases[0].description,
    tasks: tasks
};
var project = {
    _id: req.body.id,
    created: new Date(),
    creator: req.body.creator,
    phases: phases
};

var data = new ProjectTemplatesModel(project);
data.save(function (err) {
    if (err) {
      console.log(err);
      if(err.name==='ValidationError'){
        res.status(500);
        res.send("ValidationError");
      }
      if(err.code===11000){
        res.status(500);
        res.send('duplicateProject');
      }
    } else {
      res.status(200);
      res.send("success");
    }
});

});

这是ajax发布的代码:

                        $.ajax({
                                url: "/",
                                type: 'POST',
                                contentType: "application/json",
                                data: JSON.stringify(project)
                                    })
                                .done(function(event){
                                    console.log(event)
                                    if(event==='success'){
                                        window.location = '/';
                                    }
                                }).fail(function(err){
                                    console.log(err);
                                    if('duplicateProject'){
                                      $("#errorDiv").show();
                                    }
                                    if('ValidationError'){
                                      $("#errorDiv1").show();
                                    }
                                    console.log('Not successful');
                            });

它实际上显示了我在.fail()函数中定义的两个错误,但之后立即在屏幕上显示了该错误。

感谢您的帮助。

0 个答案:

没有答案