javascript - 无法让plotly + node.js 流式传输通过POST 请求发送的数据

标签 javascript node.js plotly

我正在尝试通过对 http://localhost:3000/stepPOST 请求来流式传输服务器接收到的数据。

基于plotly-nodejs/examples中的rest-example.js构建,这是我的服务器代码(我已经模糊了我的用户名、apikey和 token ):

'use strict';

var express = require('express');
var logger = require('morgan');
var bodyParser = require('body-parser');
var events = require('events');
var eventEmitter = new events.EventEmitter();

var app = express();
var server = require('http').Server(app);
var port = process.env.PORT || 3000;
server.listen(port);

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/step', function(req, res) {
    var data = req.body.data;
    eventEmitter.emit('step', data);
    res.end('ok');
});

var plotly = require('plotly')('username', 'apikey');
var token = 'token';

var dataInit = [{x:[], y:[], stream: { token: token, maxpoints: 10 } }];
var layout = {fileopt : "extend", filename : "REST-test"};

plotly.plot(dataInit, layout, function (err, msg) {
    if(err) return console.error('step data error', err.stack);

    var stream = plotly.stream(token, function() {});

    eventEmitter.on('step', function(data) {
        console.log('sending to plotly: ' + data + ' steps');

        var streamObject = JSON.stringify({ x: getDateString(), y: data });
        stream.write(streamObject+'\n');
    });
});

function getDateString() {
    var d = new Date();
    return d.toLocaleString();
};

当我使用 cURL POST 数据时,例如 curl http://localhost:3000/step --data "data=5",我可以看到数据到达plotly.plot block 内的回调,但plotly永远不会启动并传输数据。

在我之前处理的一些稍微复杂的服​​务器代码中,我还收到了可能相关也可能不相关的错误,并且该错误始终指向 plotly.plot block 的开头。

cb(null, body);
        ^
SyntaxError: Unexpected end of input

这是完整的错误堆栈:

/home/plotly-testing/node_modules/plotly/index.js:305
        cb(null, body);
        ^
SyntaxError: Unexpected end of input
    at Object.parse (native)
    at /home/plotly-testing/node_modules/plotly/index.js:72:25
    at IncomingMessage.<anonymous> (/home/plotly-testing/node_modules/plotly/index.js:305:9)
    at IncomingMessage.emit (events.js:129:20)
    at _stream_readable.js:908:16
    at process._tickCallback (node.js:355:11)
---------------------------------------------
    at IncomingMessage.Readable.on (_stream_readable.js:671:33)
    at parseRes (/home/plotly-testing/node_modules/plotly/index.js:304:9)
    at ClientRequest.<anonymous> (/home/plotly-testing/node_modules/plotly/index.js:71:9)
    at ClientRequest.emit (events.js:107:17)
    at HTTPParser.parserOnIncomingClient (_http_client.js:426:21)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:111:23)
    at TLSSocket.socketOnData (_http_client.js:317:20)
---------------------------------------------
    at new ClientRequest (_http_client.js:93:10)
    at Object.exports.request (http.js:49:10)
    at Object.exports.request (https.js:136:15)
    at Plotly.plot (/home/plotly-testing/node_modules/plotly/index.js:70:21)
    at Object.<anonymous> (/home/plotly-testing/index.js:175:8)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)

plotly/index.js的第305行指向以下方法,这似乎表明我的一个回调中出现了问题,但我不确定。

// response parse helper fn
function parseRes (res, cb) {
    var body = '';
    if ('setEncoding' in res) res.setEncoding('utf-8');

    res.on('data', function (data) {
        body += data;
        if (body.length > 1e10) {
            // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQ
            res.connection.destroy();
            res.writeHead(413, {'Content-Type': 'text/plain'});
            res.end('req body too large');
            return cb(new Error('body overflow'));
        }
    });

    res.on('end', function () {
        cb(null, body);
    });

}

最佳答案

因此,我修改了代码,在 Plotly.plot 回调中包含 console.log

请参阅此处的要点: https://gist.github.com/alexander-daniel/b36f9be78abbbaa4847e#file-index-js-L33

这样我们就可以看到 Plotly 返回了一个我们可以查看的图形 URL。 https://gist.github.com/alexander-daniel/b36f9be78abbbaa4847e#file-console_output-L5

这应该可以解决第一个问题。

就第二个问题而言,问题似乎有两个: - 库内的 JSON.parse 调用未包装在 try/catch 中,因此看起来如果流服务器返回任何非 JSON 的内容,则会中断。

我们正在调查流服务器错误返回,但我已在此处重新打开此问题:API 库中的 try/catch block 。

github.com/plotly/plotly-nodejs/issues/37

关于javascript - 无法让plotly + node.js 流式传输通过POST 请求发送的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34346996/

相关文章:

javascript - 在 VueJS 中将动态样式传递给我的元素

node.js - 为什么在某些情况下,某些版本的 Node.js 上 process.env._ 未定义?

javascript - 如何使用 Mocha 配置 TeamCity 构建?

Julia plotly

javascript - 使用 plotly.js 时如何定义 x 轴悬停格式

javascript - 在浏览器上显示小模态窗口

javascript - 头像移动不流畅

python - 像plotly.express 中一样使用plotly.graph_objs 创建直方图

javascript - 为自定义 HTML 元素创建高度和宽度属性

javascript - Angular ngRoute 导致无限循环和堆栈溢出