这与我问here的问题有关。解决方案之一是创建一个位图,而我正试图通过公开从nodejs返回SVG字符串的服务来做到这一点。我按照文档here进行操作。它正在返回包含SVG内容的响应,但svg内容似乎不正确。
NodeJS代码
const express = require('express');
const vega = require('vega');
const app = express();
app.get('/vega', (request, response) => {
const spec = JSON.parse(request.query.spec);
const view = new vega.View(vega.parse(spec), {
logLevel: vega.Warn,
renderer: 'none'
});
const svgResult = view.toSVG();
svgResult.then(function(res){
response
.set('Cache-Control', `public, max-age=${60 * 60}`)
.type('svg').send(res);
}).catch((err) => console.log("rejected:", err));
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Listening on ${PORT}`));
示例通话请求
http://localhost:3000/vega?spec=%7B%0D%0A++%22description%22%3A+%22A+simple+bar+chart+with+embedded+data.%22%2C%0D%0A++%22data%22%3A+%7B%0D%0A++++%22values%22%3A+%5B%0D%0A++++++%7B%22a%22%3A+%22A%22%2C%22b%22%3A+28%7D%2C+%7B%22a%22%3A+%22B%22%2C%22b%22%3A+55%7D%2C+%7B%22a%22%3A+%22C%22%2C%22b%22%3A+43%7D%2C%0D%0A++++++%7B%22a%22%3A+%22D%22%2C%22b%22%3A+91%7D%2C+%7B%22a%22%3A+%22E%22%2C%22b%22%3A+81%7D%2C+%7B%22a%22%3A+%22F%22%2C%22b%22%3A+53%7D%2C%0D%0A++++++%7B%22a%22%3A+%22G%22%2C%22b%22%3A+19%7D%2C+%7B%22a%22%3A+%22H%22%2C%22b%22%3A+87%7D%2C+%7B%22a%22%3A+%22I%22%2C%22b%22%3A+52%7D%0D%0A++++%5D%0D%0A++%7D%2C%0D%0A++%22mark%22%3A+%22bar%22%2C%0D%0A++%22encoding%22%3A+%7B%0D%0A++++%22x%22%3A+%7B%22field%22%3A+%22a%22%2C+%22type%22%3A+%22ordinal%22%7D%2C%0D%0A++++%22y%22%3A+%7B%22field%22%3A+%22b%22%2C+%22type%22%3A+%22quantitative%22%7D%0D%0A++%7D%0D%0A%7D
样本响应
<svg class="marks" width="0" height="0" viewBox="0 0 0 0" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g transform="translate(0,0)"><g class="mark-group role-frame root"><g transform="translate(0,0)"><path class="background" d="M0,0h0v0h0Z" style="fill: none;"></path><g></g></g></g></g></svg>
感谢任何帮助,以查找问题所在。
答案 0 :(得分:0)
通过上面的代码中的一些修复使其工作。
const express = require('express');
const vega = require('vega');
const app = express();
app.get('/vega', (request, response) => {
const spec = JSON.parse(request.query.spec);
getSVG(spec, response);
// let res = render(spec, response);
// console.log('response', res);
});
async function getSVG(spec, response) {
const view = new vega.View(vega.parse(spec), {
loader: vega.loader(),
logLevel: vega.Warn,
renderer: 'none'
})
.initialize()
.finalize();
return (view.toSVG(1))
.then(_ => {
//console.log(_);
console.log("Processed SVG request at -", Date.now());
response
.set('Cache-Control', `public, max-age=${60 * 60}`)
.type('svg').send(_);
});
}
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Listening on ${PORT}`));