Unexpected end of json input. File not able to parse completely - node.js

I have seen related questions on stack overflow as well as other websites and no solution worked out for me. I am working on a something which makes a get request. I am using expressjs and for get request i am using https module. The api from where I am making a get request is https://api.rootnet.in/covid19-in/stats/latest . I confirmed that it returns a json object. The code is:
const express = require('express');
const app = express();
const https = require('https');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.get('/', function(req, res){
const URL = 'https://api.rootnet.in/covid19-in/stats/latest';
https.get(URL, function(response){
response.on('data', function(data){
console.log(JSON.parse(data));
});
});
});
app.listen(3000, function(){
console.log("server started");
});
the output i am getting is:
server started
undefined:1
{"success":true,"data":{"summary":{"total":343091,"confirmedCasesIndian":335359,"confirmedCasesForeign":48,"discharged":180013,"deaths":9900,"confirmedButLocationUnidentified":7684},"unofficial-summary":[{"source":"covid19india.org","total":344015,"recovered":180331,"deaths":9920,"active":153721}],"regional":[{"confirmedCasesIndian":41,"confirmedCasesForeign":0,"discharged":33,"deaths":0,"loc":"Andaman and Nicobar Islands","totalConfirmed":41},{"confirmedCasesIndian":6456,"confirmedCasesForeign":0,"discharged":3316,"deaths":88,"loc":"Andhra Pradesh","totalConfirmed":6456},{"confirmedCasesIndian":91,"confirmedCasesForeign":0,"discharged":7,"deaths":0,"loc":"Arunac
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at IncomingMessage.<anonymous> (C:\Users\sasmit\Desktop\covid 19\testapp.js:15:24)
at IncomingMessage.emit (events.js:315:20)
at IncomingMessage.Readable.read (_stream_readable.js:506:10)
at flow (_stream_readable.js:1006:34)
at resume_ (_stream_readable.js:987:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
seems like it is not able to parse the entire file.

It's because the response is sent in chunks. After each chunk the data event is emitted. But it doesn't mean the response is fully sent. To make sure the reponse is complete, you need to use end event and parse the reponse then:
const URL = 'https://api.rootnet.in/covid19-in/stats/latest';
let result = '';
https.get(URL, function(response){
response.on('data', function(data){
result += data;
});
response.on('end', function() {
console.log(JSON.parse(result));
});
});

When you try to parse it as JSON it is converted to a string, which is empty, So, you can give this a try
app.get('/', function(req, res){
var URL = 'https://api.rootnet.in/covid19-in/stats/latest';
https.get(URL, function(res){
var json = '';
res.on('data', function(data){
json += data;
});
res.on('end', function(){
var response = JSON.parse(json);
console.log(" JSON Parserd ", response.success);
});
}).on('error', function(e){
console.log("Error occured while parsing ", e);
});
});

Related

node js error Cannot read property 'temp' of undefined open weather api

`const express = require("express");
const https = require("https");
const app = express();
app.get("/", function (req, res) {
const url = "https://api.openweathermap.org/data/2.5/forecast?q=delhi&appid={apikey}&units=metric";
https.get(url, function (response) {
console.log(response.statusCode);
response.on("data", function(data){
const weatherData = JSON.parse(data);
console.log(weatherData);
const Temp = weatherData.main.temp;
console.log(Temp);
});
});
res.send("server is up");
});
app.listen(3000, function () {
console.log("server is running");
});`
i am using open weather api and trying to log temprature in main object
iam getting the error:-
const Temp = weatherData.main.temp;
^
TypeError: Cannot read property 'temp' of undefined
also why does stack overflow makes it so hard to post questions
I think the query is returning a different JSON than you're expecting, it seems like it returns an object with a list of temperatures at different times, not just one 'temp'. I recommend you downloading a JSON browser extension and looking at the JSON in the browser: https://api.openweathermap.org/data/2.5/forecast?q=delhi&appid=0e9bd132a69ddc33c030e2bda11ac71f&units=metric
heres what i did
stored the list array is a variable tempList
used [tempList.length -1] to get to get the last element of the list
response.on("data", function(data){
const weatherData = JSON.parse(data);
var tempList = weatherData.list;
const Temp = tempList[tempList.length -1].main.temp;
console.log(Temp);
});

Node js(Express framework): not able to print number API from external server to client browser

I am trying to retrieve weather API from external server and when I am console logging particular data of weather API, it's also showing on my command prompt.
But when I am using get method to show that data on browser I am only able send string data like "description": moderate rain and not number data like "temp": 27
it the crash the app.
Node js code:
//jshint esversion:6
const express = require("express");
const app = express();
const https = require("https");
app.get("/", function(req, res) {
const url = "https://api.openweathermap.org/data/2.5/weather?q=mumbai&appid=d88391210768983e6be06cdd76bdcde3&units=metric";
https.get(url, function(response) {
console.log(response.statusCode);
response.on("data", function(data) {
const weatherData = JSON.parse(data);
const temp= weatherData.main.temp;
const description= weatherData.weather[0].description;
console.log(temp);
console.log(description);
res.send(temp);
});
});
});
app.listen(3000, function() {
console.log("Server is running on port: 3000");
});
You should ideally return a json.
It can be:
res.send({temp: temp, description: description});
The res.send has to return a string/object/array/buffer.
You could do something like:
res.status(200).send(temp)
But sending json response is preferable, and you can scale it as well.
Another hack kind of solution is:
res.send("" + temp)

Want to write capture and re-transmit http/https request to Browser?

I want to write a simple Node Js application which will capture and re-transmit http/https request to Browser?
I have written the below code, but it works only for http request.
var server = http.createServer(function (req,res) {
console.log("start request:", req.url);
var option = url.parse(req.url);
option.headers = req.headers;
var proxyrequest = http.request(option, function (proxyresponce) {
proxyresponce.on('data', function (chunk) {
console.log("proxy responce length" ,chunk.length);
res.write(chunk,'binary');
});
proxyresponce.on('end',function () {
console.log("proxy responce ended");
res.end();
});
res.writeHead(proxyresponce.statusCode, proxyresponce.headers);
});
});

GET request response on to Jade page?

I've managed to make a GET request to an API however now I want to get the response on to a Jade page.
Here is my code for the GET request so far. This is in 'index.js' in the routes 'folder'. Any ideas about how I can get the response on to a Jade page?
router.get('/', function(req, res) {
var url = 'http://data.police.uk/api/forces';
http.get(url, function(res){
var body = '';
res.on('data', function(chunk){
body += chunk;
});
res.on('end', function(){
var response = JSON.parse(body)
console.log("Successful")
});
}).on('error', function(e){
console.log("Error: ", e);
})
});
module.exports = router;
In your router
res.render('viewName',{"variable":"value"});
In your view
p #{variable}
Instead of trying to start from scratch, you should probably look at some sample templates for node.js with express.
http://blog.ijasoneverett.com/2013/03/a-sample-app-with-node-js-express-and-mongodb-part-1/
This would tell you how to set up the structure of the app.

Node.js, Protocol buffers - how to get the post payload so I can parse?

Clients post protocol buffers to my url. I need to get the payload to I can parse. I am using express but I will take anything that works.
app.post('/n/bidder', function(req, res){
var payload = ??????;
var mypb_schema = schema['Feeds'];
var brr_fu = mypb_schema.parse(payload);
});
Thanks
You have to receive the payload from the req input stream and combine the parts:
var buffertools = require('buffertools');
app.post('/n/bidder', function (req, res) {
var payload = [];
req.on('data', function (data) {
payload.push(data);
});
req.on('end', function () {
var payload = buffertools.concat.apply(null, payload);
var mypb_schema = schema['Feeds'];
var brr_fu = mypb_schema.parse(payload);
// rest of code here
});
});

Resources