0

I tried using other api and it worked, however it does not work with this one.

const express = require("express");
const https = require("https");
const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.get("/",(req, res)=>{
https.get("https://pixabay.com/api/?key=xxx-zzz&q=yellow+flowers&image_type=photo", (response)=>{
   console.log(response.statusCode);
       response.on("data",d=>{
           const lala = JSON.parse(d);
           console.log(lala);
       })
    
    })
});
app.listen(3000,()=>{
    console.log("Server started on port 3000")
})

I got this in the console

200
undefined:1
{"total":28739,"totalHits":500,"hits":[{"id":3063284,"pageURL":"https://pixabay.com/photos/rose-flower-petal-floral-noble-3063284/","type":"photo","tags":"rose, flower, petal","previewURL":"https://cdn.pixabay.com/photo/2018/01/05/16/24/rose-3063284_150.jpg","previewWidth":150,"previewHeight":99,"webformatURL":"https://pixaba

SyntaxError: Unexpected end of JSON input
at JSON.parse ()

3
  • Is there another console.log() that you don't show in the snippet? Where is undefined:1 coming from? Commented Nov 16, 2020 at 6:26
  • You have three outputs in the console and I can only find 2 console.logs. something is missing. And a piece of advise, never share a code snippet with sensitive info like API key. It'd be wise if you omit the API from your snippet. Commented Nov 16, 2020 at 6:30
  • 1
    @SiradjiAwoual Thank you for the adviced. I won't do it again Commented Nov 16, 2020 at 17:13

1 Answer 1

1

The data event does not mean that a request has completed. Request data is sent in packets.

Use the data event to collect all the data and then combine it in the end event before interacting with your data:

const express = require("express");
const https = require("https");
const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.get("/",(req, res)=>{
https.get("https://pixabay.com/api/?key=xxx-zzz&q=yellow+flowers&image_type=photo", (response)=>{
   console.log(response.statusCode);
       let chunks = [];
       response.on("data",d=>{
           chunks.push(d);
       });
       response.on("end",()=>{
           const lala = JSON.parse(Buffer.concat(chunks).toString('utf8'));
           console.log(lala);
       });
    });
});
app.listen(3000,()=>{
    console.log("Server started on port 3000");
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.