错误:无法读取未定义的属性'get' – node.js中的HTTPS
我有一个构buildd3-Graph
的app.js
在这个图表中有一个Update-Button
。 当button被点击时,我想调用另一个node.js文件data.js
的函数。
Update-Button looks like this: d3.select("#updatebutton").on("click", function(e) { try{ getJSON(); } catch (e) { alert('Error: ' + e); } window.parent.location = window.parent.location.href; });
如果我点击Update-Button
,抛出错误:
错误:无法读取未定义的属性'get'
get
被引用到https请求中,在data.js
执行。 执行如下:
var https = require('https'); function getJSON() { var req = https.get(options, function(response) { // handle the response var res_data = ''; response.on('data', function(chunk) { res_data += chunk; }); response.on('end', function() { //do anything with received data }); }); req.on('error', function(e) { console.log("Got error: " + e.message); }); req.end();
}
如果我自己运行data.js
(cmd:node data.js),它工作正常! 所以https-Request本身是很好的。 但是,如果我从另一个文件app.js
调用getJSON()
,我得到上面显示的错误。
如何解决这个问题?
var https = require('https'); function getJSON() {...}
var https = require('https'); function getJSON() {...}
是在客户端的代码?
我看到你正在调用getJSON();
从一个客户端代码,但它看起来像其他代码应该在服务器端,所以你将需要某种types的API被客户端代码调用,该API将返回function getJSON() {...}
的结果function getJSON() {...}
函数,例如,而不是客户端调用getJSON();
,它将是$.get('/api/endpoint', function(data) { ... });
编辑
下面是一个使用Express的API示例,所以你需要在dependencies
节点> "express": "~4.13.1",
join到你的package.json
中"express": "~4.13.1",
然后运行npm install
然后运行node app.js
假设你把这个代码放入app.js
文件
var express = require('express'); var app = express(); app.get('/api/data', function(req, res) { // you stuff goes here, getJSON function, etc // ... // ... var sample = {id: 5, name: 'test'}; res.json(sample); }); app.listen(process.env.PORT || 3000);
而你的客户端代码将需要调用这个API,例如可以通过jQuery来完成
$.get('http://localhost:3000/api/data', function(data){ // handle that 'data' on the client side here // ... // ... });