![](/img/trans.png)
[英]SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)
[英]SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) on("data")
我尝试使用其他 api 并且它有效,但是它不适用于这个。
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")
})
我在控制台中得到了这个
200
未定义: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语法错误:JSON 输入意外结束
在 JSON.parse()
data
事件并不意味着请求已经完成。 请求数据以数据包的形式发送。
使用data
事件收集所有数据,然后在与数据交互之前将其合并到end
事件中:
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");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.