我有一个简单的JSON API,由于某种原因,它会呈现另一个值,而不是console.log
报告该值的值。
我的路线:
app.get('/dateRecords', function(request, response, next) {
console.log('/dateRecords', api.dateRecords);
response.json(api.dateRecords);
});
这是我的api.js:
exports.dateRecords = exports.dateRecords || [];
exports.listData = function(req, res) {
console.log('listData:', exports.dateRecords);
return res.json(exports.dateRecords);
};
控制台输出:
listData: []
addData: [ '2014-01-22': { requestedInvites: 47 } ]
addData: [ '2014-01-22': { requestedInvites: 47, registrations: 5 } ]
getStatsForDate http://create.gootechnologies.com/api/metrics/ksa8dVWi8sPg41?mode=1&day=20140122
listData: [ '2014-01-22': { requestedInvites: 47, registrations: 5 } ]
addData: [ '2014-01-22': { requestedInvites: 47, registrations: 5 } ]
addData: [ '2014-01-22': { requestedInvites: 47, registrations: 5 } ]
getStatsForDate http://create.gootechnologies.com/api/metrics/ksa8dVWi8sPg41?mode=1&day=20140105
listData: [ '2014-01-22': { requestedInvites: 47, registrations: 5 } ]
addData: [ '2014-01-22': { requestedInvites: 47, registrations: 5 }, '2014-01-05': { requestedInvites: 49 } ]
addData: [ '2014-01-22': { requestedInvites: 47, registrations: 5 }, '2014-01-05': { requestedInvites: 49, registrations: 20 } ]
/dateRecords [ '2014-01-22': { requestedInvites: 47, registrations: 5 }, '2014-01-05': { requestedInvites: 49, registrations: 20 } ]
浏览器输出:
[]
(即exports.dateRecords
的初始值)
有什么问题?
答案 0 :(得分:2)
res.json
使用JSON.stringify
。 JSON.stringify
使用非数字键忽略数组的属性。
var a = [1,2,3];
JSON.stringify(a); // '[1,2,3]'
a.hi = 4;
JSON.stringify(a); // '[1,2,3]'
只需将常规对象而不是数组传递给res.json
。