![](/img/trans.png)
[英]illegal token when using data from res.json using Node and Express 4
[英]Extracting Information Sent Using res.json From a Node + Express API
我正在構建一個相對簡單的端點,該端點在進行簡短的數據庫查詢和計算后應返回一個數字。 問題是我不確定如何將其發送到前端,因此可以輕松地從前端訪問它。 特別是,我一直在使用res.json()
方法,但是在console.log
,它返回了一個巨大的對象,其中的數據無處可尋。
如何從API發送數據並在前端接受數據? 也就是說,我假設它將以JSON的形式出現,但是我想知道是否將其拆包。
這是代碼:
router.get('/current/:id', function(req, res){
var collection = db.get('Activity');
var started = false;
var seconds;
//Important to use findOne here to get an object back instead of an array
collection.findOne({_id : req.params.id }, function(err, activity){
if (err) throw err;
var dateNow = (new Date()).getTime();
console.log("activity in /current/:id is: " + activity);
if (activity.runtime) {
var dateStart = (Date.parse(activity.runtime.startDate));
seconds = Math.round((dateNow - dateStart) / 1000);
started = activity.runtime.started;
console.log("dateNow: " + dateNow);
console.log("dateStart " + dateStart);
console.log("seconds " + seconds);
console.log(activity.runtime.started);
} else {
started = false;
seconds = 0;
}
if (started && (seconds > 0)) {
//res.json(seconds);
console.log(res.json(seconds));
}
else {
//res.json(0);
console.log(res.json(seconds));
}
});
});
您只需要關心響應內容,就可以通過以下方式發送響應:
if (started && (seconds > 0)) {
console.log(seconds);
res.send({data : seconds});
}else {
res.send({data : 0});
}
客戶將收到的數據為:
{data : 0}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.