javascript - 错误: cannot read property 'get' of undefined - HTTPS in node.js

标签 javascript node.js function https

我有一个app.js,它构建了一个d3-Graph。在此图中有一个更新按钮。单击按钮时,我想调用另一个 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;
    });

如果我点击更新按钮,则会抛出错误:

Error: cannot read property 'get' of undefined

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() {...} 是客户端的代码吗?

我看到您正在从客户端代码调用 getJSON();,但看起来其他代码应该在服务器端,因此客户端代码需要调用某种 API,并且该 API 将返回 function getJSON() {...} 函数的结果,因此,例如,不是客户端调用 getJSON();,而是 $.get('/api/端点', function(data) { ... });

<小时/>

编辑

这是一个使用 Express 的 API 示例,因此您需要将其添加到 dependency Node 中的 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
  // ...
  // ...
});

关于javascript - 错误: cannot read property 'get' of undefined - HTTPS in node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34063308/

相关文章:

javascript - 清洁代码 : try/catch in Promise

mysql - 用于检查数据库更新的 Socket.io

node.js - 模拟请求对象不适用于 Node.js 中的测试

node.js - Node awssum 去哪儿了?

r - 将自定义函数与 tidyverse 结合使用

javascript - 无法动态推送数组值比较两个数组

javascript - 导航集成后不再显示 HTML 图像

javascript - 使用 jQuery 在多个图像上添加文字说明

php - 帮助创建一个可重用的 PHP 函数,它将 'dynamically' 调用其他函数

php - 在函数之外传递变量 php