【问题标题】:SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) on("data")SyntaxError:JSON.parse (<anonymous>) on("data") 处的 JSON 输入意外结束
【发布时间】:2021-02-27 09:11:14
【问题描述】:

我尝试使用其他 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":"玫瑰、花朵、花瓣","previewURL":"https://cdn.pixabay.com/photo/2018/01/05/16/24 /rose-3063284_150.jpg","previewWidth":150,"previewHeight":99,"webformatURL":"https://pixaba

SyntaxError:JSON 输入意外结束
在 JSON.parse() 处

【问题讨论】:

  • 还有没有在 sn-p 中显示的 console.log() 吗? undefined:1 来自哪里?
  • 您在控制台中有三个输出,而我只能找到 2 个 console.logs。缺了点什么。还有一条建议,永远不要与 API 密钥等敏感信息共享代码 sn-p。如果您从 sn-p 中省略 API,那将是明智的。
  • @SiradjiAwoual 谢谢你的建议。我不会再这样做了

标签: javascript node.js api express https


【解决方案1】:

data event 并不意味着请求已完成。请求数据以数据包的形式发送。

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

【讨论】:

    猜你喜欢
    • 2020-10-05
    • 2020-03-09
    • 2018-12-09
    • 2021-06-08
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2021-08-10
    • 2020-02-06
    相关资源
    最近更新 更多