繁体   English   中英

SyntaxError:JSON 输入意外结束 - 为什么?

[英]SyntaxError: Unexpected end of JSON input - why is that?

这是我使用 express 和 node.js 编写的代码

    const express = require("express");
    const https = require("https");
    const app = express();
    
    app.get("/", function(req, res) {
    
        // Url to my api key
         const url = "https://api.spoonacular.com/recipes/random?apiKey=...&number=1";
    
         https.get(url, function(response) {
    
              response.on("data", function (data) {
                   console.log(JSON.parse(data));
                   // const theRecipe = JSON.parse(data);
                   console.log(data);
              });
    
         });
    
         res.send("The server is up and running");
    });
    
    app.listen(3000, function () {
         console.log("Server started at port 3000");
    });

当我在 localhost 上刷新网页时,在控制台上出现以下错误:

引用 SyntaxError: Unexpected end of JSON input at JSON.parse () at IncomingMessage。 (C:\Users\ArunBohra\Desktop\FoodRecipes\app.js:12:33) 报价

谁能找到我的代码有什么问题。

当来自响应的一大块数据到达时触发 on 事件。 您正在尝试解析第一个块,就好像它是完整的 JSON 文本一样。

您需要从每个 on 事件中收集片段,但要等到结束事件后再将它们连接到您可以解析的 JSON 的完整字符串中。

您可能想查看像 axios 和 node-fetch 这样的模块,它们会为您解决这个问题(以及 JSON 解析),同时提供基于现代 Promise 的 API。

如果您使用像node-fetch这样的 package,您可以在一个 go 中获得全部内容,而不是您现在拥有的数据块

const fetch = require('node-fetch');
const url = "https://api.spoonacular.com/recipes/random?apiKey=...&number=1";
fetch(url)
  .then(response => response.json())
  .then(data => console.log(data));

除了其他答案之外,您可以在没有其他 package 的情况下做到这一点。

https.get(url, function (response) {
    let result = "";
    response.on("data", function (data) {
        result += chunk;
    });
    res.on('end', () => {
        // now you have the combined result
        console.log(result);
    });
}); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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