节点/快速路由显示错误的输出

时间:2014-12-14 22:24:34

标签: javascript json node.js express

我是Node / Express的新手,在编写一个安静的API的早期阶段,开发人员可以通过HTTP GET访问“/ zwave / devices”路径,以接收JSON格式的设备列表。

我能够通过来自其他来源的XHR请求获取原始设备JSON,并在启动应用程序时成功将其输出到控制台以进行调试,但是,当我通过浏览器访问“/ zwave / devices”时,JSON控制台中显示的输出是一个空对象{}。

启动应用程序时,我会收到我希望在控制台中的完整JSON数据。但是,当我在等待zwave.getDevicesJSON()完成后访问/ zwave / devices时,我没有。为什么呢?

提前感谢您的帮助。

server.js

// Singleton; shared state and behavior of a single class instance.
var zwave = require('./zwave.js');

// Route for /zwave/devices that should send JSON output to console for debugging.
app.get('/zwave/devices', function(req, res) {
  zwave.showDevicesJSON();         // Displays second, incorrectly; outputs {}
  console.log(zwave.devicesJSON);  // Displays third, incorrectly; outputs {}
});

var server = app.listen(http_port, function () {    
  // Initial get of device JSON data, with a callback to show JSON in the console
  zwave.getDevicesJSON(zwave.showDevicesJSON);  // Displays first, correctly; outputs JSON
});

zwave.js

function Zwave() {
  this.devicesJSON = {};    
};

Zwave.prototype.getDevicesJSON = function(callback) {  
  // Working XHR code here to obtain device JSON.
  this.devicesJSON = JSON.parse(data); 
  callback.bind(this)();
};

Zwave.prototype.showDevicesJSON = function(req,res) {  
  console.log('Show Devices Is Firing');
  console.log(this.devicesJSON);      
};

module.exports = new Zwave();

1 个答案:

答案 0 :(得分:0)

是因为你从不发送输出作为回应

尝试把这个

app.get('/zwave/devices', function(req, res) {
   zwave.showDevicesJSON();         // Displays second, incorrectly; outputs {}
   console.log(zwave.devicesJSON);  // Displays third, incorrectly; outputs {}
 res.json(zwave.devicesJSON);
});

你可以更多地关注路线

http://expressjs.com/starter/basic-routing.html

相关问题