如何从REST响应中呈现对象

时间:2017-09-02 10:23:24

标签: javascript json ajax rest cors

我想渲染到ui / print到控制台记录来自GET响应的一些对象值。

我的服务器端使用Node JS,客户端使用HTML + JS。

因为我的目标是呈现数据而请求类型是跨域的,所以我不能使用" fetch"功能。 我执行它的唯一选择是通过" JSONP"数据类型。

实际上,请求已发送,响应也通过回调接收,但我的代码是print" null"到控制台而不是响应数据。 当我尝试使用JSON.parse()时,它收到了一个" parseerror"。

预期的结果是只获取图像标记值(2.0.90)并在控制台日志中打印/将其呈现给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

1 个答案:

答案 0 :(得分:0)

您需要遍历响应以返回结果,例如..

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