javascript - How to GET JSON Object from URL in Node.js/Express -
i should preface post saying beginner , first time using node.js , express in real project.
i have simple node.js/express project , want read json object url. afterwards, intend build url displays html external website using iframe.
i read 'request' module online , know need along these lines:
var express = require('express'); var router = express.router(); var request = require('request'); // urls app center rest functions var url = 'https://someserver.com/appserver/portal/api/1.0/results/recent'; /* list of recent reports */ router.get('/testapi', function(req, res, next) { res.render('testapi', { title: 'list recent reports' }); }); /* test: function report list */ router.get('/recentreports', function(req, res){ request({ url: url, json: true }, function (error, response, body) { if (!error && response.statuscode === 200) { console.log(body) // print json response } }) });
i have tried define function /recentreports
called in testapi.jade
view, nothing printed in console when load page , suspect doing horribly wrong.
my questions are:
how read json app , code go (index.js, app.js, testview.jade etc...?)
how export url construct wherever code lives .jade view?
there nothing logged browser console because no response sent server. response logged server's console.
you'll need refactor code 'recentreports'
route send data. use simple res.send
call:
... function (error, response, body) { if (!error && response.statuscode === 200) { res.send(body) // send response client } } ...
this response received testapi.jade
via ajax call '/recentreports'
route. ajax call can defined in javascript file sourced testapi.jade
file.
the constructed url not need exported exists within same testapi.jade
file (after you've formed results ajax call).