KRL
KRL

Reputation: 125

nodejs json endpoint from api json stream

I am connecting to an api and pulling a set of json data. the javascript outputs the json as the variable feedData and when i include that in a html i get the json on a html page as expected. What i want to do is output it as a json endpoint. I tried to get fancy and when i tried:

var express = require('express');
var app = express();
app.get('/', function (req, res) {
  res.send(feedData);
});
app.listen(3000, function () {
 console.log('posting data');
});

the problem is that i need to import an api.js file and when i attempt to load this i get an error related to the api.js file which is windows is not defined. Like i said, the html

 document.getElementById('mydiv').innerHTML += JSON.stringify(feedData, undefined,2);

then

<pre id="mydiv"></pre>

works fine but i will also to recall every x seconds because this is a live json feed.

Currently, i just decided to connect via python, loading it into mongodb and creating a nodejs endpoint from there, which works fine, but it seems there should be a way here.

Upvotes: 1

Views: 216

Answers (2)

Vlad B.
Vlad B.

Reputation: 2937

Instead of

res.send(feedData);

use

res.json(feedData);

Hope this helps

Upvotes: 1

dcodesmith
dcodesmith

Reputation: 9614

Try using res.json, res.json(feedData); to send objects. If you want to send a string just, use res.send

Upvotes: 1

Related Questions