簡體   English   中英

錯誤:無法讀取未定義的屬性“ get”-node.js中的HTTPS

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

我正在構建一個d3-Graphapp.js 此圖中有一個Update-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引用在data.js執行的https請求。 實現如下:

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:節點data.js),則工作正常! 因此,https-Request本身很好。 但是,如果我從其他文件app.js調用getJSON() ,則會收到上面顯示的錯誤。

如何解決這個問題?

var https = require('https'); function getJSON() {...} var https = require('https'); function getJSON() {...}該代碼在客戶端嗎?

我看到您正在調用getJSON(); 從客戶端代碼,但看起來其他代碼應該在服務器端,因此您將需要某種類型的API來由客戶端代碼調用,並且該API將返回function getJSON() {...}的結果function getJSON() {...}函數,例如,而不是客戶端調用getJSON(); $.get('/api/endpoint', function(data) { ... });


編輯

這是一個使用Express的API示例,因此您需要將其添加到dependencies節點> "express": "~4.13.1",中的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
  // ...
  // ...
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM