0

データベースにを追加する際に問題が発生し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;

これは、新しいデータベース エントリを作成する最初の行の 1 つであるため、そのプロパティを読み取れなかった場合、データベースに追加されません。それは私の考えでしたが、インデックス ページをリロードすると、新しいデータベース エントリが表示されるのに、なぜ機能していないと思いますか?

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 @ ビュー (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

team.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.bodyJavaScript オブジェクトに解析されていない ( JSON 文字列のままである ) ためだと思います。まず、使用しているかどうかを確認してください

app.use(express.bodyParser());

どのルートよりも前。そうでない場合は、set.ajaxの代わりに使用してみてください。.postcontentType

$.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 に答える