从REST API获取数据到jsreports

Get data from REST API to jsreports

本文关键字:jsreports 数据 获取 REST API      更新时间:2023-09-26

我可以成功地从下面的脚本中获取数据并显示在报告中。

function beforeRender(done){
    require("request")({url:"http://nicolas.kruchten.com/pivottable/examples/mps.json",json:true},function(err, response, body){
        request.data = {posts:body};
        done();
    })    
}

我用了这个,

<h1>Request</h1>
<table style='border-style:solid'>
  <tr>
    <th>Province</th>
    <th>Party</th>
    <th>Name</th>
  </tr>
  {{for posts}}
  <tr>
    <td>{{:Province}}</td>
    <td>{{:Party}}</td>
    <td>{{:Name}}</td>
  </tr>  
  {{/for}}    
</table>

但是当我使用以下查询调用REST api时,它会在控制台获取数据并写入,但不会显示在报告中。

var request = require('request');
function beforeRender(done){
    require('request')({headers: {
    'sToken': 'qq',
    'log': 'dd'
  }, url: 'http://localhost:3000/com.dd.com/Inventory' , json:true },
    function(error, response, body) {
        request.data = {posts:body};
         console.log(request.data );
        done();
    });
}

HTML代码

<h1>Request</h1>
<table style='border-style:solid'>
  <tr>
    <th>Name</th>
  </tr>
   {{for posts}}
  <tr>
    <td>{{:Name}}</td>
  </tr>  
    {{/for}}    
</table>

JSON字符串返回:

{ posts:
   { Id: '700',
     Name: 'myName',
     __osHeaders:
      { Version: '{EFF95F4C-2FA2-11E5-BA94-040150C75001}',
        Namespace: 'com.dd.com',
        Class: 'Inventory',
        Tenant: '123',
        LastUdated: '2015-07-21 08:20:56.197248204 -0400 EDT' } } }

使用引擎:jsrender
配方:phantom-pdf

如何在报表中显示值?在使用API时,我在哪里出错了?

我发现了这个问题。我注释掉了下面一行,这导致我没有把它打印在报告上。

var request = require('request');

因此新代码是

//var request = require('request');
    function beforeRender(done){
        require('request')({headers: {
        'sToken': 'qq',
        'log': 'dd'
      }, url: 'http://localhost:3000/com.dd.com/Inventory' , json:true },
        function(error, response, body) {
            request.data = {posts:body};
             console.log(request.data );
            done();
        });
    }

第一个API返回一个数组,然后与jsrender for循环一起工作。

但是根据你发布的JSON字符串第二个API返回一个对象,这就是为什么for循环不工作在那里。没有for循环也可以用:<h1>{{:posts.Name}}</h1>

所以解决方案是改变API调用实际接收数组或转换输出到它,这样你就可以循环。