Get parameters through Json via POST



  • Hello good afternoon!

    I'm testing JsReport 2.4.0, I found the maximum tool, but I'm not able to get parameters that I send via POST, that is, I need to do a POST and get custom parameters to use in a GET within the Script in Layout. It's quite simple, I'll go through exactly the example below:

    1 - I am sending via POST my URI (http://192.168.2.220:3100/api/report) the JSON below:

     {
    	"template": {
    		"recipe":"phantom-pdf",
    		"engine":"handlebars",
    		"contentType": "application/json",
    		"shortid":"j~CwowY"
    	},    
    	"options": { "reportName": "myreportparams" },
    	"scripts":[ { "shortid":"jAGaUdm" } ],
    	"reports": { "save": true },
    	"data":null,
    	"params": [{ "chave":"RQ96HSnCByXeddf", "titulo":"RD37" }]
     }
    
    • I wanted to grab the JSON tag "params" and capture the two "key" and "title" elements to concatenate in a URL which will make a GET in an API.

    Follows my script where it has got to be done, I already tested with static variables and it works, however I need to receive these parameters via POST in some way.

    var getRequest = require('request').get
    
    function beforeRender(req, res, done){
    
    	// var chave = 'RQ96HSnCByXeddf'
    	// var titulo = 'RD37'
    
    getRequest('https://xxxxxxxxxxxx/apiRDlead/RDlead.php?chave=' + chave + '&titulo=' + titulo, 
    	 
    	function (err, resp, body) {
    		if (err) {
    			return done(err)
    		}
    		req.data = JSON.parse(body)
    		done()
    	})    
    }
    

    So how could I capture this json and handle the variables so I do the GET already mount with these parameters?

    Tanks!!!


  • administrators

    hi! this is possible if you send the params in the data property

    {
    	"template": {
    		"recipe":"phantom-pdf",
    		"engine":"handlebars",
    		"contentType": "application/json",
    		"shortid":"j~CwowY"
    	},    
    	"options": { "reportName": "myreportparams" },
    	"scripts":[ { "shortid":"jAGaUdm" } ],
    	"reports": { "save": true },
    	"data": {
               "params": [{ "chave":"RQ96HSnCByXeddf", "titulo":"RD37" }]
             }
     }
    

    then in your script just do:

    var getRequest = require('request').get
    
    function beforeRender(req, res, done){
    
    	var chave = req.data.params[0].chave
    	var titulo = req.data.params[0].titulo
    
    getRequest('https://xxxxxxxxxxxx/apiRDlead/RDlead.php?chave=' + chave + '&titulo=' + titulo, 
    	 
    	function (err, resp, body) {
    		if (err) {
    			return done(err)
    		}
    		req.data = JSON.parse(body)
    		done()
    	})    
    }
    


  • Good Morning. I'll take the test as past and post worked out. Thank you very much.



  • My friend, gave the code right. Thank you very much.


Log in to reply
 

Looks like your connection to jsreport forum was lost, please wait while we try to reconnect.