简体   繁体   中英

SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) on("data")

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 ()

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");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM