2016-11-03 8 views
0

は、私のような投稿する要求を使用します。がHTTPレスポンスからJSONオブジェクトが、undefiend

まず私はオプション

var ops = { 
     'user':'johnny', 
     'password':'password' 
    }; 

はその後、私のような要求を行うます

{"user":"johnny","time":"2016-11-03T15:58:34.444Z"} 
request.post({url: endpoint, formData: ops}, function(err, res, body){ 
      console.log(res.body); 
     }); 

これは、私はAPIから必要なデータを返します。

しかし、私はへの要求を変更すると、その後:

request.post({url: endpoint, formData: ops}, function(err, res, body){ 
       console.log(res.body.user); 
      }); 

私は戻って、「未定義」を取得。

ユーザーが明らかにオブジェクトの属性である場合、res.bodyにアクセスできますが、res.body.userにアクセスできないのはなぜですか?

おかげ

+0

あなたは、ログインすることができますにconsole.log(res.body.user)とはconsole.log(res.body)で同じ時間と応答を投稿します。 – JainAnk

+0

'console.log(typeof res.body);とは何ですか? – Quentin

+0

あなたの応答が文字列であるからです。それを 'JSON'に変換してください – krakig

答えて

0

、これはトリックを行いますあなたの応答文字列である:

var data = JSON.parse(res.body); 
console.log(data.user); 
関連する問題