1

I want to render to the ui / print to console log some object value from GET response.

I'm using Node JS for my server side and HTML + JS for my client side.

Because my goal is to render data and the request type is cross domain I can't use "fetch" function. My only alternative to execute it is to send it by "JSONP" dataType.

Actually, the request is sent and the response receives by callback as well, but my code is print "null" to the console and not the response data. When I've tried to used JSON.parse() it received a "parseerror".

The expected result it's to get only the image tag value (2.0.90) and to print this inside the console log / render it to the UI.

 async function uiChecking() {
    let index;
    const hostsDock = [qa + dockers];
    let lengthVal = hostsDock.length;
    for (let hostIndxD = 0; hostIndxD < lengthVal; hostIndxD++) {
        index = hostIndxD;
        let url = hostsDock[hostIndxD];

        $.ajax({
            url: url,
            dataType: 'jsonp',
        }).done( function(data) {
            console.log("A " + data);
        });

    }
}

**Server.js **

var express = require('express');
var cors = require('cors');
var app = express();
var path = require("path");
var fetch = require('fetch-cookie')(require('node-fetch'));
var btoa = require('btoa');
var http = require('http');


var corsOptionsDelegate = function (req, callback) {
    var corsOptions;
    if (whitelist.indexOf(req.header('Origin')) !== -1) {
        corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
    }else{
        corsOptions = { origin: false } // disable CORS for this request
    }
    callback(null, data , corsOptions) // callback expects two parameters: error and options
};

app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/view');
app.set('view engine', 'html');


app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res){
    res.render('index');
    res.render('logo');
    res.writeHead(200, {'Content-Type': 'application/json'});
});

// app.get('/products/:id', cors(corsOptionsDelegate), function (req, res, next) {
//     res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
// });


app.get('/data/:id', function (req, res, next) {
    var opts = {
        host: config.alertService.host,
        port: config.alertService.port,
        method: 'GET',
        path: '/DataService/rest/receiveData/' + req.params.id
    }

    var reqGet = http.request(opts, function (dataResponse) {
        var responseString = '';
        dataResponse.on('data', function (data) {
            responseString += data;
        });
        var response = {x:[],y:[],z:[],t:[]};
        dataResponse.on('end', function () {
            var responseObject = JSON.parse(responseString);
            var accs = responseObject.data.listPCS;
            for(var i in accs){
                response.x.push(accs[i].accX);
                response.z.push(accs[i].accY);
                response.y.push(accs[i].accZ);
                response.t.push(accs[i].timestamp);
            }
            res.jsonp(response);
        });
    });
    reqGet.end();
    reqGet.on('error', function (e) {
        console.error(e);
    });
});

if (app.settings.env === 'production') {
    app.error(function(err, req, res) {
        res.render('new404.html', {
            status: 500,
            locals: {
                error: error
            }
        });
    });
}

app.listen(8033, function () {
    console.log('CORS-enabled web server listening on port 8033')
});

enter image description here

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Idan E
  • 1,299
  • 4
  • 17
  • 42
  • Cant you access the object already? like; `success: function (data) { console.log(data[0].id); }` etc – keja Sep 02 '17 at 10:26
  • it doesn't work as well, it receive "parseerror" and console to log - {readyState: 4, setRequestHeader: ƒ, getAllResponseHeaders: ƒ, getResponseHeader: ƒ, overrideMimeType: ƒ, …} – Idan E Sep 02 '17 at 10:28
  • This doesn't need to be an async function. –  Sep 02 '17 at 11:00
  • Still doesn't render the response data, now it receive "undefined" :/ @programmer5000 – Idan E Sep 02 '17 at 17:52
  • 1
    `app.listen(8033, …)` in the node.js code & `cannot load production.com:2375/containers/json … localhost:8033 is therefore not allowed access` in the error message indicate that port 8033 server is serving your frontend code and is sending a request to a different server running at `production.com:2375`. So it doesn’t matter what CORS config you’ve done on the port 8033 server—because it’s not the server your frontend code is sending your request to. Instead you need to add CORS support to the `production.com:2375` server—because that’s the server you’re actually sending the request to. – sideshowbarker Sep 06 '17 at 20:07

1 Answers1

0

You need to iterate through the response to return the result e.g..

$.each(data, function(index) {
    console.log(data[index].ui);
    console.log(data[index].id); console.log(data[index].Name);
});
Arkay
  • 56
  • 4