我正在将 JSReport 集成到 Node JSApplication 中。JSReport 使用几个 3rd 方 api 来显示图表等。当我单独运行 JSReporn 时,它工作得很好。在此处输入图像描述
当我使用 Node JS 应用程序运行时,它不显示图表。在此处输入图像描述
在这里我附上了我的代码在 jsreport studio 模板是:
<h1>{{country}}</h1>
<canvas id='orders' style="margin-top:30px"></canvas>
<table class="table striped">
<thead>
<tr>
<th>OrderID</th>
<th>ShipAddress</th>
<th>ShipCity</th>
<th>ShipCountry</th>
</tr>
</thead>
<tbody>
{{#each orders}}
<tr>
<td>{{OrderID}}</td>
<td>{{ShipAddress}}</td>
<td>{{ShipCity}}</td>
<td>{{ShipCountry}}</td>
</tr>
{{/each}}
</tbody>
</table>
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.min.js'></script>
<script>
var data = {{{toJSON this}}}
Chart.defaults.global.legend.display = false;
var orders = document.getElementById("orders").getContext('2d');
var chartObj = new Chart(orders, {
type: 'bar',
data: {
labels: Object.keys(data.accumulatedOrders),
datasets: [{
fillColor: 'blue',
label: "Orders in time",
backgroundColor: "rgba(27,161,226,0.2)",
borderColor: "rgba(27,161,226,1)",
borderWidth: 1,
hoverBackgroundColor: "rgba(27,161,226,0.4)",
hoverBorderColor: "rgba(27,161,226,1)",
data: Object.keys(data.accumulatedOrders).map(function (o) {
return data.accumulatedOrders[o].value;
})
}]
},
options: {
animation: {
onComplete: function () {
// set the PDF printing trigger when the animation is done
// to have this working, the phantom-pdf menu in the left must
// have the wait for printing trigger option selected
//window.JSREPORT_READY_TO_START = true
}
}
}
});
</script>
Script code is :
// custom server side script used to fetch data from remote REST API
var http = require('http');
function getOrders(country, cb) {
http.get({
hostname: 'services.odata.org',
port: 80,
path: `/V4/Northwind/Northwind.svc/Orders?$filter=${encodeURI(`ShipCountry eq '${country}'`)}`,
}, (result) => {
var str = '';
result.on('data', (b) => str += b);
result.on('error', cb);
result.on('end', () => cb(null, JSON.parse(str)));
});
}
function beforeRender(req, res, done) {
// the report parameter country can be send from the client API request
req.data.country = req.data.country || 'France'
getOrders(req.data.country, (err, json) => {
if (err) {
return done(err);
}
var orders = json.value;
var ordersByQuarter = {};
orders.forEach((o) => {
o.OrderDate = new Date(o.OrderDate);
var key = o.OrderDate.getFullYear() + '/' + (o.OrderDate.getMonth() + 1);
ordersByQuarter[key] = ordersByQuarter[key] || {
value: 0,
orderDate: o.OrderDate
};
ordersByQuarter[key].value++;
});
req.data.orders = orders;
req.data.accumulatedOrders = ordersByQuarter;
done();
});
}