0

我在向我的数据库添加 a 时遇到问题team,我现在有一个索引页面,它现在只显示数据库中的所有团队。当我转到localhost:3000/team下面看到的这个时team.jade,我输入团队名称并按下提交按钮。然后当我转到索引页面时,它就在那里,我的新团队就在那里。

但是当我按下提交按钮时,我实际上收到一条错误消息:

Express
500 TypeError: Cannot read property 'teamName' of undefined
at module.exports (/home/declan/nodeapps/tournamentManager/routes/index.js:126:24)
at callbacks (/home/declan/nodeapps/tournamentManager/node_modules/express/lib/router/index.js:160:37)
at param (/home/declan/nodeapps/tournamentManager/node_modules/express/lib/router/index.js:134:11)
at pass (/home/declan/nodeapps/tournamentManager/node_modules/express/lib/router/index.js:141:5)
at Router._dispatch (/home/declan/nodeapps/tournamentManager/node_modules/express/lib/router/index.js:169:5)
at Object.router (/home/declan/nodeapps/tournamentManager/node_modules/express/lib/router/index.js:32:10)
at next (/home/declan/nodeapps/tournamentManager/node_modules/express/node_modules/connect/lib/proto.js:190:15)
at Object.handle (/home/declan/nodeapps/tournamentManager/app.js:34:5)
at next (/home/declan/nodeapps/tournamentManager/node_modules/express/node_modules/connect/lib/proto.js:190:15)
at Object.static (/home/declan/nodeapps/tournamentManager/node_modules/express/node_modules/connect/lib/middleware/static.js:55:61)

我不知道为什么我得到这个,第 126 行index.js实际上是下面的这一行:

var name = teamForm.teamName;

这是创建新数据库条目的第一行之一,因此如果它无法读取该属性,则不会将其添加到数据库中。那是我的想法,但是当我重新加载索引页面时,有我的新数据库条目,那么您为什么认为它不起作用?

index.js @ 路由

/**
  * Add a new Team to database
  */
  app.post('/team', function(req, res) {
    util.log('Serving request for url[GET] ' + req.route.path);
    var teamForm = req.body.teamForm;
    var name = teamForm.teamName;

    var newTeam = new Team();
    newTeam.name = name;

    newTeam.save(function(err, savedTeam){
      var message = '';
      var retStatus = '';
      if(!err){
        util.log('Successfully created team with Name : ' + name);
        message = 'Successfully created new team : ' + name;
        retStatus = 'success';
      } else {
        util.log('Error while creating team : ' + name + ' error : ' + util.inspect(err));
        if(err.code === 11000){
          message = 'Team already exists';
        }
        retStatus = 'failure';
      }
      res.json({
        'retStatus' : retStatus,
        'message' : message
      });
    });
  });

team.jade @views(html模板,你可以看到需要的id等)

extends index

block content
    div.row-fluid
        div.span9
            h2 New Team
            div.well.sidebar-nav
                div.teamList
                    form.form-horizontal(method="post", id="team-form")
                        div.control-group
                            label.control-label(for="teamName") Team Name :
                            div.controls
                                input.input-small(type="text", id="teamName")
                        div.control-group
                            div.controls
                                button#teamConfirm.btn.btn-primary.btn-mini(href='#') To DB
                br
                p This page is used to demonstrate how an 8 team single elimination tournament would be represented in the final design of my project. The pseudo code conjured up in my initial hand-in document was originally used here to produce the same result. The pseudo code helped create this set of seeded brackets, so that the matches correspond to the seeds of the tournament. For the 8 team bracket, I worked back through from the final, where seeds 1 and 2 should face each other, until I was left at round 1 of the brackets. This was used to give myself a 'new' set of seeds which were in the correct order to just be placed into these brackets.
        div.span3
            div.well.sidebar-nav
                h4 To-Do List:
                p - Enter list of teams manually from this page.
                p - Do a test to show a bracket with random seed.
                p - Show rankings after tournament

团队.js@js

var newTeam = function(){
    $('#teamConfirm').click(function(){
        newTeam.teamForm();
    });
};

newTeam.teamForm = function(){

    var teamForm = {
        teamName : $('#teamName').val()
    };
    // Basic validation
    $.post('/team', {'teamForm' : teamForm}, function(response) {
            console.log(response);
    });
};

newTeam();

index.js@js

var Main = {};

Main.loadScript = function(url){
  var footer = document.getElementById('footer');
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = url;

  footer.appendChild(script);
}

$(document).ready(function(response){
  Main.loadScript('js/login.js');
  Main.loadScript('js/signup.js');
  Main.loadScript('js/team.js');
});
4

1 回答 1

0

我认为这是因为req.body没有被解析为 JavaScript 对象(它仍然是 JSON 字符串)。首先检查你是否在使用

app.use(express.bodyParser());

任何路线之前。如果不是这样,请尝试使用.ajax而不是.postwith contentTypeset:

$.ajax({
    // some other settings
    contentType : "application/json"
});

可能是内容类型搞砸了,Express 没有解析从客户端接收到的 JSON 字符串。您可能会尝试的另一件事是简单地做(在​​服务器端):

app.post('/team', function(req, res) {
    var body = JSON.parse( req.body );
    // other code
}

也许用try{}catch{}块包装附加行。

于 2012-12-23T13:21:24.430 回答