无法在本地计算机上的远程计算机上打开HTML文件

时间:2019-03-18 04:51:49

标签: javascript html node.js d3.js client-server

我有一个通过腻子使用的虚拟机(ubuntu 16.04)。 我有一个带有服务器脚本learning_server.js的服务器文件夹,它看起来像(node-nodule是文件夹) `

var version = '2019 March';
console.log('NodeJS Server - '+version);
/* ************************************** */

// ================== load nodejs packages =================
var http = require('http');
var https = require('https')
var async = require('async');
var ip = require("ip");
var url = require('url');
var fs = require('fs');
var request = require('request');
var moment = require('moment');
let fastcsv = require('fast-csv');

// ================== server port =================
var port = 5000;

// ================== load raw data =================
var inputDataFile = "data/AoT_Chicago.complete.2019-03-17/nodes.csv";

let readableStreamInput = fs.createReadStream('./'+inputDataFile);
let csvData = [];
var updatedData = [];
let minVal=1, maxVal=25;

// As the input file is CSV, using fast-csv node module to read the contents and save it to an a array.
fastcsv
    .fromStream(readableStreamInput, {headers: true})
    .on('data', (data) => {
      let rowData = {};

      Object.keys(data).forEach(current_key => {
         rowData[current_key] = data[current_key];
      });
      csvData.push(rowData);
    })
    .on('end', () => {
        console.log('No of rows read: ', csvData.length);

        // ================== server setup ==================
        var server = http.createServer();
        server.on('request', request);
        server.listen(port, '0.0.0.0');
        console.log('Server IP is '+ip.address() + ' port '+port)
        console.log('Server is Ready...')
        function request(request, response) {
            var store = '';

            // Start processing the contents of the http request
            request.on('data', function(data) { store += data; });

            // Once we reach the end of the http request, start creating the response to send to the client.
            request.on('end', function() {
                try {
                    response.setHeader('Content-Type', 'application/json');
                    response.setHeader("Transfer-Encoding", "chunked");
                    response.setHeader("Access-Control-Allow-Origin", "*");
                    response.setHeader("Access-Control-Allow-Methods", "POST");
                    response.setHeader("Access-Control-Allow-Headers", "Content-Type");

                    // As long as the client sends a valid request with key "data_request" in it, server returns the whole data as JSON string in the response.
                    var jsonData = JSON.parse(store);

                    if(jsonData.hasOwnProperty('data_request')){
                        let retn = JSON.stringify(csvData);
                        response.end(retn);
                        console.log('data sent')
                        updatedData=csvData;
                    } else if(jsonData.hasOwnProperty('updated_data_request')){
                        // To simulate the condition where the data sent by the server changes based on key words in the client request,
                        // data is randomly generated if the request has "updated_data_request" as key.
                        updatedData=[];
                        for (i = 0; i < csvData.length; i++) {
                            var rowData = {};
                            var val=Math.floor(Math.random() * (maxVal - minVal + 1)) + minVal;
                            rowData["number"]=val;
                            updatedData.push(rowData);
                        }

                        let retn = JSON.stringify(updatedData);
                        response.end(retn);
                        console.log('updated data sent')
                    } else if(jsonData.hasOwnProperty('deleted_data_request')){
                        // To simulate the condition where the data sent by the server is same as previous request but some points are removed now.

                        var index=Math.floor(Math.random() * (updatedData.length));
                        updatedData.splice(index,1);
                        let retn = JSON.stringify(updatedData);
                        response.end(retn);
                        console.log('deleted data sent')
                    }

                } catch(error) {
                    // server error, need be re-run
                    console.log('*** ERROR: Server error ***');
                    console.log(error);
                }
            });
        }
    })
`

我还有一个带有我的客户端脚本learning_client.js的客户端文件夹,它看起来像(节点结点是文件夹)

`var version = '2019 March';
/* ************************************** */

// server's ip address (same machine in this case)
var serverIP = 'localhost';
// Port number on which server is listening
var serverPort = '5000';

// Function to create a request for the server
function reqJSON(jsonData) {
    return $.ajax({
                type: "POST",
                url: "http://"+serverIP+":"+serverPort,
                cache: false,
                crossDomain: true,
                data: jsonData,
                processData: false,
                dataType: 'json',
                headers: {
                    "Content-Type":"text/plain;charset=UTF-8",
                },
                timeout: 15000, // 15s
            })
};

var colorCounter=0;
colors=['green','blue','red']
updateData("data_request");

function updateData(request_key) {
    console.log(request_key);
    // Use given key to request the data from server
    var request_obj = {};
    request_obj[request_key]={}
    req = JSON.stringify(request_obj)
    console.log(req);
    // Create the request
    reqJSON(req).then(function(data, error){

        // Got the response from the server. "data" contains the data returned by the server
        console.log(data);

        // Start creating visualization using "data"

        var scale = d3.scaleLinear()
                        .range([5,15])
                        .domain(d3.extent(data, function(d){return d.number;}))

        var svg=d3.select("svg");
        svg.style("background-color", "white");

        var svg_rect=svg.node().getBoundingClientRect();

        // Create circles for each data point
        var datapoints=svg.selectAll("circle")
            .data(data)

        //Enter section: Invoked only for creating the new data points
        datapoints.enter().append("circle")
            .attr("cx", function(d,i) {return 50*(i+1) + 5;})
            .attr("cy", svg_rect.y+svg_rect.height/2)
            .attr("r", function(d) {return scale(d.number);})
            .style("fill", colors[colorCounter%colors.length]);

        //Update section: Invoked only for upating the existing data points
        datapoints.transition()
            .duration(500)
            .attr("cx", function(d,i) {return 50*(i+1) + 5;})
            .attr("cy", svg_rect.y+svg_rect.height/2)
            .attr("r", function(d) {return scale(d.number);})
            .style("fill", colors[colorCounter%colors.length]);

        //Exit section: Invoked only for deleting the removed data points.
        datapoints.exit().remove();

        //Create text showing the number that represents the corresponding circle.
        var datapointsText = svg.selectAll("text")
            .data(data)

        //Enter section
        datapointsText.enter().append("text")
            .attr("x", function(d,i) {return 50*(i+1) + 5;})
            .attr("y", svg_rect.y+svg_rect.height/2+50)
            .style("text-anchor", "middle")
            .style("font-size", "1em")
            .text(function(d) {return d.number;});

        //Update section
        datapointsText
            .attr("x", function(d,i) {return 50*(i+1) + 5;})
            .attr("y", svg_rect.y+svg_rect.height/2+50)
            .style("text-anchor", "middle")
            .style("font-size", "1em")
            .text(function(d) {return d.number;});

        //Exit section
        datapointsText.exit().remove();

        colorCounter++;
    })

}
`

并且我有一个带有html(learning_index.html)文件的html文件夹

`<!doctype html>
<html>
<head>
    <title>Simple Client Demo (NodeJS)</title>
    <meta charset="utf-8">
    <link href="/home/ricky/D3js/css/style.css" rel="stylesheet" media="screen" type="text/css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="http://d3js.org/d3.v5.min.js" charset="utf-8"></script>
</head>

<body>
    <div class="MainVis">
        <svg width="1080" height="200"></svg>
    </div>
    <div class="update">
        <input name="updateButton" 
           type="button" 
           value="UPDATE" 
           onclick="updateData('updated_data_request')" />
        <input name="deleteButton" 
           type="button" 
           value="DELETE" 
           onclick="updateData('deleted_data_request')" />
    </div>
    <script type="text/javascript" src="./js/learning_client.js"></script>
</body>
</html>
`

通过腻子,我可以使用node server/js/learning_server.js启动服务器 输出显示为

`NodeJS Server - 2019 March
No of rows read:  91
Server IP is 10.158.56.133 port 5000
Server is Ready...
`

现在我正在尝试使用本地Windows计算机打开learning_index.html文件

`http://10.158.56.133:5000/D3js/client/html/learning_index.html`
but it shows 
`This site can’t be reached 10.158.56.133 took too long to respond.
Search Google for 158 133 5000 D3js client html learning index
ERR_CONNECTION_TIMED_OUT`

你能告诉我我在做什么错吗?

1 个答案:

答案 0 :(得分:1)

我的第一个猜测是Ubuntu VM上的防火墙阻止了端口5000。

默认情况下,您应该在ubuntu计算机上安装一个名为“ Uncomplicated Firewal(UFW)”的工具。

运行以下命令应允许远程计算机连接到该端口:

sudo ufw allow 5000

运行该命令后,您可以在浏览器中再次尝试查看是否可以访问该页面。