PokeAPI issue, can't get data

So I am trying to use PokeAPI for educational purposes and I run this:

const express = require('express') const https = require('https') const app = express() const port = 3000  app.get('/', function(req,res){     const url = 'https://pokeapi.co/api/v2/berry'                 //no uses el mismo nombre de argumentos     https.get(url, function(resp) {         resp.on('data', function(data){             let datos = JSON.parse(data)             console.log(datos)         })     })     res.send('lol') })    app.listen(port, () => console.log(`Example app listening on ${port} port!`)) 

And in the console I got this:

undefined:1 {"count":64,"next":"https://pokeapi.co/api/v2/berry?offset=20&limit=20","previous":null,"results":[{"name":"cheri","url":"https://pokeapi.co/api/v2/berry/1/"},{"name":"chesto","url":"https://pokeapi.co/api/v2/berry/2/"},{"name":"pecha","url":"https://pokeapi.co/api/v2/berry/3/"},{"name":"rawst","url":"https://pokeapi.co/api/v2/berry/4/"},{"name":"aspear","url":"https://pokea     SyntaxError: Unexpected end of JSON input     at JSON.parse (<anonymous>)     at IncomingMessage.<anonymous> (C:\UdemyWeb\PokeProject\app.js:11:30)     at IncomingMessage.emit (events.js:311:20)     at IncomingMessage.Readable.read (_stream_readable.js:512:10)     at flow (_stream_readable.js:989:34)     at resume_ (_stream_readable.js:970:3)     at processTicksAndRejections (internal/process/task_queues.js:84:21) 

I’ve been asking around the internet, I even asked on their slack and got no responses, I think is the way I’m fetching the data from the API but I want to know why just with this API and not with others, I’ve tried with weatherAPI and D&D API and no problems at all. Thanks.

Add Comment
1 Answer(s)

I bet the problem also occurs with others apis. Maybee the other responses were to small so they all arrived with the first chunk. I would recommend to use some http library like axios. If you want to handle the chunks by your own, you have to aggreagte all the data and listen for the end event.

let data = ''; resp.on('data', function(chunk) {     data += chunk; });  resp.on('end', function() {     console.log(JSON.parse(data)); }); 

Another good read i would recommend you is 5 Ways to Make HTTP Requests in Node.js

Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.