2016-09-01 54 views
0

我需要的是在客戶端的「數據」字段中發送英雄對象。誰在Nodejs的數據字段中發送響應數據

這是我的代碼的NodeJS:

app.get('/heroes', (req, res) => { 
    getHeroes().then(function (heroes) { 
     res.json(heroes); 
    }, function (error) { 
     console.log("Error: " + error); 
    }); 
}); 

英雄是一個JavaScript對象,我從MongoDB中獲得。

客戶看到這樣的內容:

_body: "[{"name":"dsfsdf","id":"1"},{"name":"fhghfgh","id"…{"name":"sdff","id":"1"} 

誰存儲的英雄數據屬性,而不是_body?

在此先感謝。

+0

分享預期產出! –

+0

不要忘記在錯誤情況下響應HTTP請求,否則請求將無限期地掛起。 – josh3736

回答

1

response.json()函數需要一個JSON對象。您提供了一個JSON對象數組,而不是一個JSON對象本身。您需要聲明您想要分配數據的JSON項目。沒有明確的聲明,它默認爲_body

你可以做這樣的事情:

app.get('/heroes', (req, res) => { 
    getHeroes().then(function (heroes) { 
     res.json({ "data": heroes }); 
    }, function (error) { 
     console.log("Error: " + error); 
    }); 
}); 

我希望這有助於!

+0

謝謝,但是我需要的是存儲數據響應porperty中的英雄,而不是:_body:「{」data「:[{」name「:」dsfsdf「,」id「:」1「} – ayoseturru

+0

當我運行代碼,我沒有得到「_body」假設你的代碼返回到'_body',然後使用'res.json({「data」:heroes._body})' – nickcorin

1
app.get('/heroes', (req, res) => { 
    getHeroes().then(function (heroes) { 
     res.json({"data": heroes._body }); 
    }, function (error) { 
     console.log("Error: " + error); 
    }); 
}); 
+0

請解釋你的代碼對於其他人閱讀你的答案。 –