2017-08-28 15 views
3

ExpressJSで構築されたユーザー登録ページがあります。ユーザーがここに入力したデータは、外部Api(Java Rest API)に渡す必要があります。しかし、私は受信側でJSONデータを取得していません。また、私はユーザーを作成した後にのみ応答を送信する必要があります。以下のコードスニペットです:ここExpress JSから渡された外部APIのJSONデータがありません

は私ExpressJSコードです:(私はここでJSONデータを投稿するポストマンのアプリを使用しています)

router.post('/register', function(req, res, next) { 
    console.log(req.body); // JSON sent from Postman is showing correctly 

    var options = { 
     method: 'POST', 
     uri: 'http://localhost:3000/userCreation', 
     body: req.body, 
     json: true, 
     headers: { 'Content-Type': 'application/json' } 
    } 
    // Here rp is require('request-promise'); 
    rp(options).then(function (res){ 
     console.log("Response from external Api: "+res); 
    }) 
    .catch(function (err) { 
     console.log(err); 
    }) 
    // The response below should be ideally sent after the User Registration is done. 
    // So it should go into the "then" block. But I am an unable to put it there. 
    // It says "cannot send header twice" 
    res.send('Json Data sent to Java/MongoDB & User Created successfully.'); 

}); 

これは、受信側(のJava APIでのコードである - しかし、のために今、私は別のExpressJSアプリがフローをテストする):

router.post('/userCreation', function(req, res, next) { 
    console.log("User registration in MongoDB"); 
    console.log(req.hostname); // O/p : localhost 
    console.log(req.body);  // O/p : undefined 
    res.send("User successfully created in MongoDB"); 
}); 

これに関する助けや助言は本当に役立つでしょう。前もって感謝します。

+0

あなたは 'json'を使っていますが、' text'を返すとします。おそらく 'res.json'を使ってください。 –

+0

はい、あなたは正しいです - 私はそれを変更する必要があります。しかし実際の問題はそれ以前の "rp(options)"ステートメントにあります。ここでは、JSONデータを持つ本体が含まれていますが、もう一方の端では受信されません。 – Jimmy

答えて

1

私は答えを得ました..... "app.use(bodyParser.json())"は、ExpressJSサーバーの両方のインスタンスで必要でした。今それは正常に動作しています。

関連する問題