dnks23
dnks23

Reputation: 369

Error: cannot read property 'get' of undefined - HTTPS in node.js

I'm having an app.js which builds a d3-Graph. In this Graph there is a Update-Button. When the Button is clicked I want to call a function of another node.js file 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;
    });

If I click on Update-Button the Error is thrown:

Error: cannot read property 'get' of undefined

The get is referred to an https request, performed in data.js. Implemented as the following:

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();

}

If i run data.js on it's own (cmd: node data.js) it's working fine! So the https-Request itself is good. But if i call the getJSON() from the other file app.js I get the Error shown above.

How to fix this?

Upvotes: 2

Views: 4199

Answers (1)

mkinawy
mkinawy

Reputation: 375

var https = require('https'); function getJSON() {...} is that code on the client-side?

I see that you are calling getJSON(); from a client-side code, but it looks like the other code should be on the server-side, so you will need some sort of API to be called by the client-side code, and that API will return the results of the function getJSON() {...} function, so for example instead of the client-side call to getJSON();, it would be $.get('/api/endpoint', function(data) { ... });


EDIT

Here is an API sample using Express, so you need to add that into your package.json in the dependencies node > "express": "~4.13.1", and run npm install then node app.js assuming you put this code in app.js file

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);

and your client side code will need to call that API, that could be done via jQuery for example like this

$.get('http://localhost:3000/api/data', function(data){
  // handle that 'data' on the client side here
  // ...
  // ...
});

Upvotes: 1

Related Questions