2017-03-16 2 views
0

私はREST APIノード/エクスプレスアプリで作業しています。ユーザーがapiを使用してサービスにサインアップする「サインアップ」ルートでは、POSTされたJSONオブジェクトが必要です。この関数の中で、mongo dbに対してこのユーザーがまだ存在していないことを確認する必要があります。特急でのreq.body値へのアクセス

問題は、投稿されたjson情報からユーザー名を取得する必要がありますが、すべての試みは失敗しました。 req.body.usernameとreq.body.passwordを記録しようとする行は、常に 'undefined'を返します。私は間違って何をしていますか?

ここで私がこれまで持っているコードだが、以下の通りです:急行でデフォルトで

exports.signup = function(req, res) { 

    // todo: somehow verify that username, password, email and phone number are all provided. 
    // do not write into the collection unless we know all the information has been provided. 
    // maybe access the JSON elements to make sure they are not null 
    // todo: also make sure a record doesn't already exist for this uer 

    var user = req.body; 

    // need to get the username here somehow 
    var JSONuser = JSON.stringify(user); 
// console.log('user: ' + user); 
    console.log('userJSON: ' + JSON.stringify(user)); 
    console.log('username: ' + req.body.username); 
    console.log('password: ' + req.body.password); 

    db.collection('users', function(err, collection){ 
    //if (collection.findOne({})) { // make sure the user doesn't already exist here 
     collection.insert(user, {safe:true}, function(err, result){ 
      if(err){ 
      res.send({'error':'An error has occured'}); 
      } else { 
      console.log('Success: ' + JSON.stringify(result[0])); 
      res.send(result[0]); 
      } 
     }) 
    //} 
    }); 
} 

答えて

0

、あなたは、ドットシンタックスを通じてこれらの変数にアクセスすることはできません。あなたは応答を解析する必要があります。幸いなことに、私たちはそのためのパッケージを持っています。

ポスト変数に簡単にアクセスできるように、body-parserミドルウェアを使用してください。

// install it 
bash$: npm install body-parser  

// require it in your project 
bodyParser = require('body-parser'); 

// `use` it in your express app 
app.use(bodyParser.urlencoded({ extended: true})); 

// now you your post values are available on the req.body.postVariableName 

これを私のプロジェクトのほぼすべてで使用しているだけで、簡単に行えます。

* EDIT *

私はあなたのレポを見て、それが解析された値の読み取りを関係するようにすべてが実際に正常に見えます。しかし、彼らはあなたがconsole loggingのように、あなたが混乱している場所にいるかもしれません。あなたのサインインルートを書き換えて、私はより良い説明ができるようになりました。

exports.signin = function(req, res) { 

    var user = req.body; 
    console.log('req.body: ' + JSON.stringify(user)); 
    console.log('Signing In As User: ' + user.username); 
    console.log('Password: ' + user.password); 
    res.send('You just signed in!'); 

} 

これをテストしたところ、別の端末を開いてJSONポストをカールしました。

curl -H "Content-Type: application/json" -X POST -d '{"username":"testuser","password":"testpassword"}' http://localhost:3000/signin 

ご覧のとおり、正常に動作するはずです。

いくつか言及する価値があります。 console.log('req.body: ' + req.body);と書いたとき。あなたはあなたが望むデータを見るつもりはありません。 javascriptはこれを単に識別子であるreq.body.toString()としてレンダリングするので、出力にはreq.body: [object]が表示されます。コードを投稿する場合は、JSON.stringify(req.body)を使用するか、console.dir(req.body)を使用してください。

次に、req.bodyは、本体オブジェクトにアクセスします。

// this is just user.toString() which is again [object] 
console.log('Signing In As User: ' + user); 

// You need to use the dot syntax to get user.username 
console.log('Signing In As: " + user.username); 

あなたのコードのためではなく、あなたが投稿をローカルホストにしているので、問題がまだ見えている場合。

+0

私はそれをオンラインで読んで、app.jsファイルをセットアップしましたが、それでもコンソール出力に「未定義」と表示されています。私の主なapp.jsファイルのペーストビンは次のとおりです:http://pastebin.com/raw/5kSn8eLE 私がまだ問題に遭遇している理由についての洞察はありますか? – user1250991

+0

githubにレポを持っていますが、コードに問題は見られません。もっと見る必要があります。 – magreenberg

+0

確かに、見ていただきありがとうございます。githubはhttps://github.com/aaronhesse/restapitestにあります。 – user1250991

関連する問題