2016-08-30 5 views
0

mongooseからのエラーを含む自己作成アレイを送信しようとしています。それはのような配列を作成しますExpressからAngular2にJSON配列を送信

student.save(function(err, student) { 
    if(err) 
     var errors = []; 
     for (field in err.errors) { 
      errors.push({error: err.errors[field].message}) 
     }; 
     res.contentType('application/json').status(500).send(JSON.stringify(errors)); 
    res.status(200).json(student); 
}); 

:ここ はコードです

[ { error: 'Error, expected `_id` to be unique. Value: `111111` }, 
{ error: 'Error, expected `email` to be unique. Value: `[email protected]` } ] 

をしかし、それはangular2に送信されたとき、それは文字列として保存されている

_body: "[{"error":"Error, expected `_id` to be unique. Value: `111111`"},{"error":"Error, expected `email` to be unique. Value: `[email protected]`"}]" 
headers: ... 
ok: false 
status: 500 
statusText: "OK" 
type: 2 
url: ... 

で私はちょうどAngular2でコンソールに 'err'を記録しようとしている瞬間です。しかし、私はJSON.parseをやってみましたが、私はこのエラーを受け取ります:EXCEPTION: SyntaxError: Unexpected token o in JSON at position 1

またExpressで私はすべてのアイデアは

EDIT angular2コード理解される代わり.send(JSON.stringify(errors));

.json(errors);を試みたアレイ送信の多くの異なる方法試みた:

err => console.log(err) 

私はJSON.parse(err)を試してみました。private errors = [];を試してみましたが、そのarに 'err'を挿入しました光線が、変化し、私はまだこのようなものを試してみてください同じ結果

答えて

0

をGT何も...

student.save(function(err, student) { 
    if (err) { 
    var errors = []; 
    for (var field in err.errors) { 
     errors.push({ 
     error: err.errors[field].message 
     }); 
    } 
    return res.contentType('application/json').status(500).send(errors); 
    } 
    res.status(200).json(student); 
}); 
+0

は ''際に、印刷にconsole.log(ERR)あなたは何を得る同じ結果 –

+0

を動作しませんでしたか?あなたが 'エラー '値を得る場所からあなたの質問に角度コードを入れることができますか? – abdulbarik

+0

angular2の 'console.log(err)' ???それはこれを生成するものです: '_body:" [{"error": "エラー、_id'が一意であると期待しています。値: '111111'"}、{"エラー": "エラー、予期した'電子メールが一意であること。値: 'テストの@ test.com' "}]" ヘッダ:... OK:偽 状況:500 STATUSTEXT: "OK" タイプ:2 URL:...'メイン記事に言及すべての結果を '_body'に保存しますか? –

関連する問題