2

I'm trying to load a function that returns a JSON to me on an HTML page in order to create a table.

Is is there a way to be able to launch that function and the JSON body of return insert it in a variable present in the HTML to be able to transform it into a table?

odatafunction.js

let Request = require("request");
const EventEmitter = require("events").EventEmitter;
const risultato = new EventEmitter();
let keys;
function createArrayKey(array, object) {
    let key = Object.keys(object);
    for (let i = 0; i < Object.keys(object).length; i++) {
        if(i === 0){
            array += object[key[i]];
        }else{
            array += "," + object[key[i]];
        }

    }
    return array;
}

function removeDuplicates(array, key) {
    let lookup = {};
    let result = [];
    array.forEach(element => {
        if (!lookup[element[key]]) {
            lookup[element[key]] = true;
            result.push(element);
        }
    });
    return result;
}


function check_missing_value(new_object2, max_key) {
    var breakLoop = false;
    var miss;
    for(var i=0; i<Object.keys(new_object2).length ; i++){
        miss = -1;
        for(var j = 0; j < Object.keys(max_key).length && !breakLoop ;j++){
            //console.dir(max_key[j]);
            if(!Object.keys(new_object2).includes(max_key[j])){
                new_object2[max_key[j]]="NULL";
                breakLoop = true;
            }

            }
        }


    return new_object2;
}
function retriveData(){
    const http = Request("https://services.odata.org/V3/OData/OData.svc/PersonDetails?$format=json",
        (error, response, body) => {
            if (error) {
                return console.dir(error);
            }
            let json_body = JSON.parse(body);
            let value_json = json_body.value;
            let new_json = [];
            var html = '<table class="table table-striped">';
            html += '<tr>';
            //console.dir(Object.keys(value_json[0]));
            let max_key = (Object.keys(value_json[0]));
            keys = max_key;
            for (var i = 0; i < Object.keys(keys).length; i++) {
                html += '<th>' + keys[i] + '</th>';
            }
            html += '</tr>';
            for (let i = 0; i < Object.keys(value_json).length; i++) {
                let new_object2 = {};
                let element = value_json[i];
                html += '<tr>';
                for (var j = 0; j < Object.keys(element).length; j++) {

                    var temp = Object.keys(element);
                    switch (typeof element[temp[j]]) {
                        case "object":
                            var array = createArrayKey("", element[temp[j]]);
                            new_object2[temp[j]] = array;
                            html += '<td>' + array + '</td>';
                            break;
                        case "number":
                            new_object2[temp[j]] = element[temp[j]];
                            html += '<td>' + element[temp[j]] + '</td>';
                            break;
                        case "string":
                            new_object2[temp[j]] = element[temp[j]];
                            html += '<td>' + element[temp[j]] + '</td>';
                            break;
                        case "boolean":
                            new_object2[temp[j]] = element[temp[j]];
                            html += '<td>' + element[temp[j]] + '</td>';
                            break;
                        case "bigint":
                            new_object2[temp[j]] = element[temp[j]];
                            html += '<td>' + element[temp[j]] + '</td>';
                            break;
                    }

                }
                html += '<tr>';
                new_object2 = check_missing_value(new_object2, max_key);
                new_json.push(new_object2);
            }
            html += '</table>';
            removeDuplicates(new_json, 'PersonID');
            risultato.data = new_json;
            risultato.emit('update');
            console.dir(html);
        });
    risultato.on('update', function () {
        //console.log(risultato.data); // HOORAY! THIS WORKS!
    });
    return risultato.data;
}


define({
     results : retriveData()
});
module.exports.retriveData = retriveData;

index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
  //res.sendFile('index.js');
});

module.exports = router;

index.ejs

 <!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script data-main="javascripts/odatafunction.js" src="requirejs.js"></script>
    <script type="text/javascript" >
      var trs = require(function (require){
        var test = require("javascripts/odatafunction.js");
        return{
          myfunc: function () {
              test.retriveData();
                    }
        }
      });
      odatafunction = require(["odatafunction"]);
      var data = odatafunction.retriveData;
      $(document).ready(function () {
        var html = '<table class="table table-striped">';
        html += '<tr>';
        var flag = 0;
        $.each(data[0], function (index, value) {
          html += '<th>' + index + '</th>';
        });
        html += '</tr>';
        $.each(data, function (index, value) {
          html += '<tr>';
          $.each(value, function (index2, value2) {
            html += '<td>' + value2 + '</td>';
          });
          html += '<tr>';
        });
        html += '</table>';
        $('body').html(html);
      });
    </script>
  </body>
</html>
  • are you converting JSON data twice? I mean, you are parsing json first in `retriveData()`, then you parse the html result again... At least that's what it looks like. – GrafiCode Dec 10 '19 at 11:05
  • as for the error, shouldn't you require request? `const Request = require('request');` – GrafiCode Dec 10 '19 at 11:08
  • The first time i convert the json taken from odata, in the same function i add the missing key fields (or in any case this is the intention). sorry i figured now that i left a sample creation for the table inside the odatafunction. i will remove it if necessary – claudio gugliotta Dec 10 '19 at 11:08
  • The intention is to take the json in odatafunction.js and retrive the output in html to create a table. const Request = require('request'); where i should use it ? – claudio gugliotta Dec 10 '19 at 11:09
  • in `odatafunction.js`, you are using request in that file – GrafiCode Dec 10 '19 at 11:12
  • it is in the file, was a bad formattation of my code. – claudio gugliotta Dec 10 '19 at 11:14
  • An alternative o you'r problem is a module called node-fetch, which allows node to make http fetch request like in js es6 ^^ – Ionut Eugen Dec 10 '19 at 11:16
  • there is a problem with `requirejs`, function `require()` is rewritten by that module. Please refer to this question for some explaination: https://stackoverflow.com/questions/32122705/requirejs-takes-over-node-require-function – GrafiCode Dec 10 '19 at 11:18
  • thanks for the suggestion, i tryied to change this. At the moment i see no difference in the execution. by the way if i try to launch the application from prompt i cannot access the resources. when i try to set the body i retrive only an empty object – claudio gugliotta Dec 10 '19 at 12:51

0 Answers0