Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
174
rated 0 times [  178] [ 4]  / answers: 1 / hits: 11499  / 4 Years ago, tue, june 16, 2020, 12:00:00

I am using an API for some information to display on my web page using https.get() in nodejs. But when I try to console log the response by parsing it as JSON this error is shown




SyntaxError: Unexpected end of JSON input
at JSON.parse ()
at IncomingMessage. (C:UsersHardik AggarwalDesktopRSCapp.js:17:33)
at IncomingMessage.emit (events.js:315:20)
at addChunk (_stream_readable.js:295:12)
at readableAddChunk (_stream_readable.js:271:9)
at IncomingMessage.Readable.push (_stream_readable.js:212:10)

at HTTPParser.parserOnBody (_http_common.js:132:24)
at TLSSocket.socketOnData (_http_client.js:469:22)
at TLSSocket.emit (events.js:315:20)
at addChunk (_stream_readable.js:295:12)




The URL is sending the correct data in JSON format. The only problem is that JSON.parse() is not working on this data. The code is



app.get(/, function(req, res){
https.get(url, JSON, function(response){
response.on(data, function(data){
const currency=JSON.parse(data);
console.log(currency);
})
})

res.render(index);
})

More From » node.js

 Answers
7

When you use data event it means you treat response like a stream and it is not guaranteed that it will send all the data in one chunk. So, in data event you should collect all the chunks and in end event you should try to parse the data. Also, don't forget to check response.statusCode for error.
Try this:



app.get(/, function(req, res){

https.get(url, JSON, function(response){
var data;
response.on(data, function(chunk) {
if (!data) {
data = chunk;
} else {
data += chunk;
}
});

response.on(end, function() {
const currency=JSON.parse(data);
console.log(currency);
res.render(index);
});
});

[#3476] Friday, June 12, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
saulthomasb

Total Points: 326
Total Questions: 98
Total Answers: 93

Location: Jordan
Member since Sun, Dec 26, 2021
2 Years ago
saulthomasb questions
Fri, Feb 19, 21, 00:00, 3 Years ago
Wed, Oct 23, 19, 00:00, 5 Years ago
Thu, Jan 31, 19, 00:00, 5 Years ago
Tue, Dec 4, 18, 00:00, 6 Years ago
;